ALTER TABLE  #temp add @i numeric(18,2) null

请问怎样在添加列时的列名可以用变量,因为我需要添加用户输入的数量,并每个列名按日期的天数

解决方案 »

  1.   

    declare @s varchar(100)
    set @s='ALTER TABLE  #temp add '+rtrim(@i)+' numeric(18,2) null'
    exec @s
      

  2.   

    不支持, 可以用动态语句解决
    EXEC(N'ALTER TABLE  #temp add ' + @i + ' numeric(18,2) null')
      

  3.   

    declare @sql nvarchar(200)
    set @sql='ALTER TABLE #temp ADD ['+rtrim(@i)+'] numeric(18,2) null'
    exec(@sql)
      

  4.   

    create  table tb(col int)
    insert tb
    select 1select * from tb
    /*
    col         
    ----------- 
    1
    */
    alter table tb add  col2 int default 2 --默认值
    insert tb(col)
    select 2select * from tb
    /*
    col         col2        
    ----------- ----------- 
    1           NULL
    2           2
    */
    drop table tb
      

  5.   

    值是计算出来的,是有两个列的值相加的,可以写成 default a+b 这样的吗
      

  6.   

    create  table tb(col int)
    insert tb
    select 1select * from tb
    /*
    col         
    ----------- 
    1
    */
    alter table tb add  col2 as  col*2 --默认值
    insert tb(col)
    select 2select * from tb
    /*
    col         col2        
    ----------- ----------- 
    1           3
    2           4
    */
    drop table tb