sql添加具有变量名称的列

时间:2017-04-06 06:14:14

标签: sql sql-server

有没有办法向表中添加可变数量的列。

我正在尝试下面但没有成功。

DECLARE @VAR INT = 1
WHILE @VAR <=20
BEGIN
    DECLARE @COLUMN VARCHAR(MAX) = 'COLUMN_'+CAST(@VAR AS VARCHAR)
    IF NOT EXISTS(SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('MY_TBL') AND name=@COLUMN )
        begin
        ALTER TABLE MY_TBL ADD @COLUMN NVARCHAR(3) NULL;
        end
    SET @VAR += 1
END

2 个答案:

答案 0 :(得分:1)

您需要使用动态SQL。 请尝试以下代码。

DECLARE @VAR INT = 1
WHILE @VAR <=20
BEGIN
    DECLARE @COLUMN VARCHAR(MAX) = 'COLUMN_'+CAST(@VAR AS VARCHAR)
    IF NOT EXISTS(SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('MY_TBL') AND name=@COLUMN )
        begin
        declare @sql varchar(100)= ' ALTER TABLE MY_TBL ADD '+@COLUMN+' NVARCHAR(3) NULL;' 
        exec(@sql);
        end
    SET @VAR += 1
END

答案 1 :(得分:0)

对于SQL-Server:

格式:

SELECT COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_CATALOG = 'database' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'table' 

示例:

SELECT COUNT(*) 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_CATALOG = 'imDB' AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'MovieName'

您可以将其存储在变量中并相应地使用它。

我希望你明白:)