How to create a table with dynamic table name

  • Hi all,

    Can anyone help me in this....

    I am trying to use a CREATE TABLE Command and where the table name is specified, I'm using a variable..like

    CREATE TABLE @mytable

    This @mytable could be anything...my problem is CREATE TABLE command is not recognizing this variable...even if I pass the arguments in the variable...I'll appreciate if someone here writes couple of lines of code for me how it can be done...I'm sure there is a way and I'm new to SQL Server.

    Thanx

    Muneeb.

  • This was removed by the editor as SPAM

  • Hi,

    You would have to make use of dynamic sql.

    Like so:

    DECLARE @tablename SYSNAME

    SET @tablename = 'MyTable'

    EXEC( 'CREATE TABLE ' + @tablename + ' (Id INT NOT NULL PRIMARY KEY, Col1 CHAR(10) )' )

    SELECT Id, Col1 FROM MyTable

    DROP TABLE MyTable

    /rockmoose


    You must unlearn what You have learnt

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply