Can table and column names be passed as variabales in CREATE TABLE statememnt

  • Ladies & Gentl.

    Is it possinble to create a table where column and table name are passed as variables ? Any help will greatly apprecciate. Many thanks in advavannce.

    Code Example:

    DECLARE

       @TABNAME VARCHAR(30),

       @COLNAME

     BEGIN

          CREATE TABLE @TABNAME (@COLNAME INT NULL, COL2 VARCHAR(20))

    END

    GO

     

     

     

  • You can use dynamic SQL like this:

    DECLARE

       @TABNAME VARCHAR(30),

       @COLNAME VARCHAR(30),

       @COL2 VARCHAR(30),

       @sql VARCHAR(4000)

    BEGIN

          SET @TABNAME = 'Table1'

          SET @COLNAME = 'Col1'

          SET @COL2 = 'Col2'

          SET @sql = 'CREATE TABLE ' + @TABNAME + '(' + @COLNAME + ' INT NULL, ' + @COL2 + ' VARCHAR(20))'

          EXEC (@SQL)

    END

    GO

     


    When in doubt - test, test, test!

    Wayne

  • Wayne,

    Many thanks for the recommendation. I greatly appreciate it. Have a great day!

    Sincerely yours,

    Hung Hoang:

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

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