IF EXISTS 在 SQL Server 游标中不起作用
我有一个工作正常的光标,但是当它到达脚本的这一部分时,即使该表不存在,它似乎仍然运行更新:
SET @sql = 'IF (EXISTS (SELECT * FROM ps_vars_' + @datasetid + '))
BEGIN
UPDATE ps_vars_' + @datasetid + '
SET programming_notes = replace(programming_notes, ''Some of the variables listed are source variables.'')
END';
EXEC SP_EXECUTESQL @sql
我缺少什么? #datasetid 变量也正确传入。
I have a cursor which works fine but when it gets to this part of the script, it seems to still run the update even though the table doesn't exists:
SET @sql = 'IF (EXISTS (SELECT * FROM ps_vars_' + @datasetid + '))
BEGIN
UPDATE ps_vars_' + @datasetid + '
SET programming_notes = replace(programming_notes, ''Some of the variables listed are source variables.'')
END';
EXEC SP_EXECUTESQL @sql
What am I missing? The #datasetid variable gets passed in correctly too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将
EXISTS
与表名一起使用来查看该表是否存在时,您实际上是在尝试访问该表 - 该表不存在。这就是您收到错误的原因,而不是因为您的UPDATE
语句。尝试这样做:
然后考虑一下您的数据库设计可能存在什么问题,需要您使用这样的动态 SQL。也许你的设计正是它需要的那样,但根据我的经验,十分之九(可能更多)这种代码是糟糕设计的症状。
When you use the
EXISTS
with the table name to see if the table exists you're actually trying to access the table - which doesn't exist. That's why you're getting an error, not because of yourUPDATE
statement.Try this instead:
Then think about what might be wrong with your database design that requires you to use dynamic SQL like this. Maybe your design is exactly how it needs to be, but in my experience 9 out of 10 times (probably much more) this kind of code is a symptom of a poor design.