紧急提问 exec 与在sql查询器区别的问题

cpp2017 2004-10-17 05:32:48
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)



以上这段代码执行会出错,因为我动态在#temp中加了个字段,但是好象没有应用
但把以上代码不用exec直接执行可以
加go也不行

谁能帮解决,不胜感激!!!!!(对不起各位,只有30分了)
...全文
140 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
yjdn 2004-10-17
  • 打赏
  • 举报
回复
还有,改成这样又可以执行成功,
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就不行了,怪了
yjdn 2004-10-17
  • 打赏
  • 举报
回复
为什么会报错呢,看语法也没错啊
cpp2017 2004-10-17
  • 打赏
  • 举报
回复
TO: zjcxc(邹建) 大哥
可以了 ,多谢!!
to: hdhai9451(※★開拓者...脚妞伤了☆※)
这样不行
zjcxc 元老 2004-10-17
  • 打赏
  • 举报
回复
直接执行加 go 的方式当然没有问题啦.
zjcxc 元老 2004-10-17
  • 打赏
  • 举报
回复
无论是你那个,还是楼主那个,都报错
cpp2017 2004-10-17
  • 打赏
  • 举报
回复
TO: zjcxc(邹建) 大哥

直接执行
在add column后加go可以
zjcxc 元老 2004-10-17
  • 打赏
  • 举报
回复
to: hdhai9451(※★開拓者...脚妞伤了☆※)

不会吧? 测试会报错的.
zjcxc 元老 2004-10-17
  • 打赏
  • 举报
回复
--应该改成这样

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 行)
--*/
Andy__Huang 2004-10-17
  • 打赏
  • 举报
回复
結果﹕ 1
Andy__Huang 2004-10-17
  • 打赏
  • 举报
回复
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)
zjcxc 元老 2004-10-17
  • 打赏
  • 举报
回复
--不用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' 无效。
--*/

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧