--不用exec一样出错--测试
 select 1 as i into #temp;alter table #temp add id int identity(1,1);select id from #temp;drop table #temp;/*--测试结果(所影响的行数为 1 行)服务器: 消息 207,级别 16,状态 3,行 8
列名 'id' 无效。
--*/

解决方案 »

  1.   

    declare @sql nvarchar(1000)
     
    set @sql ='select 1 as i into temp;alter table temp add id int identity(1,1);select id from temp;drop table temp'
    exec(@sql)
      

  2.   

    --应该改成这样declare @sql nvarchar(1000)
     
    set @sql =' select 1 as i into #temp;exec(''alter table #temp add id int identity(1,1)'');select id from #temp;drop table #temp;'
    exec(@sql)/*--测试结果
    (所影响的行数为 1 行)
    (所影响的行数为 1 行)id          
    ----------- 
    1(所影响的行数为 1 行)
    --*/
      

  3.   

    to: hdhai9451(※★開拓者...脚妞伤了☆※) 不会吧? 测试会报错的.
      

  4.   

    TO: zjcxc(邹建) 大哥直接执行
    在add column后加go可以
      

  5.   

    TO: zjcxc(邹建) 大哥
    可以了 ,多谢!!
    to: hdhai9451(※★開拓者...脚妞伤了☆※) 
    这样不行
      

  6.   

    还有,改成这样又可以执行成功,
    declare @sql nvarchar(1000)
     
    set @sql =' select 1 as i into #temp;
    alter table #temp add id int identity(1,1);
    select * from #temp;drop table #temp;'
    exec(@sql)--为什么把*改成id就不行了,怪了