在 while 循环中将新列添加到 SQL 服务器 table
Add new columns to a SQL Server table within a while loop
declare @a int, @min date, @max date,@i int = 0, @columnname nvarchar(max),@b nvarchar(7) = 'aa'
select @min = min([Starting Date]) from [Quantities&Planning]
select @max = max([Finish Date]) from [Quantities&Planning]
set @a = DATEDIFF(DAY,@min,@max)
while @i < @a
begin
set @i = @i +1
set @b = str(@i)
set @columnname = 'alter table Test1 add ' + @b + ' decimal(18,2) NULL'
PRINT @columnname
exec (@columnname)
end
我的代码没有按预期工作。基本上我想创建以数字命名的新列,例如 1,2,3,4,5...这是错误代码:
Warning: Null value is eliminated by an aggregate or other SET operation.
Warning: Null value is eliminated by an aggregate or other SET operation.
Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.
Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.
Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.
EXEC
旁边的 variable
周围需要 括号
...........
exec (@columnname)
...........
或者你可以SP_EXECUTESQL
执行框架DDL查询,它不需要括号但是变量应该是NVARCHAR
类型
...........
EXEC SP_EXECUTESQL @columnname
...........
要调试查询,您可以在执行前使用 PRINT
语句
...........
PRINT @columnname
exec (@columnname)
...........
declare @a int, @min date, @max date,@i int = 0, @columnname nvarchar(max),@b nvarchar(7) = 'aa'
select @min = min([Starting Date]) from [Quantities&Planning]
select @max = max([Finish Date]) from [Quantities&Planning]
set @a = DATEDIFF(DAY,@min,@max)
while @i < @a
begin
set @i = @i +1
set @b = str(@i)
set @columnname = 'alter table Test1 add ' + @b + ' decimal(18,2) NULL'
PRINT @columnname
exec (@columnname)
end
我的代码没有按预期工作。基本上我想创建以数字命名的新列,例如 1,2,3,4,5...这是错误代码:
Warning: Null value is eliminated by an aggregate or other SET operation. Warning: Null value is eliminated by an aggregate or other SET operation.
Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.Msg 2812, Level 16, State 62, Line 11
Could not find stored procedure 'alter table Test1 add decimal(18,2) NULL'.
EXEC
variable
周围需要 括号
...........
exec (@columnname)
...........
或者你可以SP_EXECUTESQL
执行框架DDL查询,它不需要括号但是变量应该是NVARCHAR
类型
...........
EXEC SP_EXECUTESQL @columnname
...........
要调试查询,您可以在执行前使用 PRINT
语句
...........
PRINT @columnname
exec (@columnname)
...........