Dynamically create table

  • Does anyone know how to dynamically create a table when you do not know in advance the number of columns or the column names?

    I have been trying to do the following without any luck on SQL Server 7

    DECLARE @Column1nvarchar(8)

    DECLARE @Column2nvarchar(8)

    DECLARE @sqlnvarchar(100)

    SET @Column1 = 'First'

    SET @Column2 = 'Second'

    SET @sql = 'CREATE TABLE Dynamic (' + @Column1 +' as int, '

    SET @sql = @sql + @Column2 +' as int)'

    EXEC (@SQL)

    I get the following error for the EXEC command

    Incorrect syntax near ')'

  • Hey Johmar,

    You have your CREATE TABLE statement slightly wrong.

    When you define the Column names, remove the 'as' keyword.

    You only need

    CREATE TABLE Dynamic (First int, Second int)

    With that removed, it works!

    Clive Strong

    clivestrong@btinternet.com

  • Bugger Me it works. I can't believe it was as simple as that.

    Thanks cstrong... your a real life saver 🙂

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

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