日期:2014-05-18  浏览次数:20553 次

动态添加列
SQL code

DECLARE @COLS INT

SET @COLS= 32-DAY(GETDATE()+32-DAY(GETDATE()))

WHILE (@COLS>0)
    BEGIN
           ALTER TABLE KQB ADD @COLS CHAR(10)
           SET @COLS=@COLS-1
    END



Msg 102, Level 15, State 1, Line 7
'@COLS' 附近有语法错误。

麻烦大侠们帮看下ALTER TABLE KQB ADD @COLS CHAR(10) 这句应当怎么改写


------解决方案--------------------
SQL code

DECLARE @COLS INT
SET @COLS= 32-DAY(GETDATE()+32-DAY(GETDATE()))
DECLARE @STR VARCHAR(100)
SET @STR=''
WHILE (@COLS>0)
BEGIN
SET @STR='ALTER TABLE KQB ADD ['+ltrim(@COLS)+'] CHAR(10)'
print @str
exec(@STR)
SET @COLS=@COLS-1
END

------解决方案--------------------
SQL code

DECLARE @COLS INT,
        @strSql varchar(1000)

SET @COLS= 32-DAY(GETDATE()+32-DAY(GETDATE()))

WHILE (@COLS>0)
    BEGIN
          set @strSql = ' ALTER TABLE KQB ADD ['+ convert(varchar(4),@@COLS) + '] CHAR(10)'
          exec (@strSql)
          SET @COLS=@COLS-1
    END