简体   繁体   中英

Add a column, with a derived column name, to an existing table in SQL Server 2014

DECLARE
    @countFlag INT,
    @maxNum INT = 5,
    @addingName NVARCHAR(6)

SET @countFlag = 1

WHILE (@countFlag <= @maxNum)
    BEGIN
        SET @addingName = 'name' + CAST(@countFlag AS NVARCHAR(2))

        ALTER TABLE TableName
        ADD
        @addingName NVARCHAR(30)

        SET @countFlag = @countFlag + 1
    END
========================================================

This is called at the beginning of a set of procedures. @maxNum is actually passed in based on a question to the operator and changes the 'shape' of an existing db to include more columns. I would like to have the resulting column names be something like "name1" "name2" etc. but I am getting an "Incorrect syntax near '@addingName'" after the ADD statement when I execute it. What am I doing wrong here?

You cannot do it in that way, you should compose the query dynamically and execute it with Exec:

DECLARE @sqlCommand varchar(200)

SET @sqlCommand = 'ALTER TABLE TableName ADD ' + @addingName + ' NVARCHAR(30) '

EXEC (@sqlCommand)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM