SQL Server 中的游标和更新
当我尝试在 SQL Server 2005 中执行此代码时,收到一条错误消息:
消息 156,级别 15,状态 1,第 20 行
关键字“close”附近的语法不正确。
消息 102,第 15 级,状态 1,第 21 行
“dbname”附近的语法不正确。
我的代码有什么问题吗?
DECLARE @name nvarchar(max), @stat nvarchar(max)
set @stat = N'update DBNAME.dbo.Ad
set Label = ''Special Ad'' where Label =''AdXXXX'''
DECLARE dbname CURSOR FOR select name from sys.databases where name like '%config%'
open dbname
begin try
while 1=1
begin
fetch next from dbname into @name
set @stat=REPLACE(@stat,'DBNAME',@name)
exec sp_executesql @stat
end
end try
close dbname
deallocate dbname
I'm getting an error message when I'm trying to execute this code in SQL Server 2005:
Msg 156, Level 15, State 1, Line 20
Incorrect syntax near the keyword 'close'.
Msg 102, Level 15, State 1, Line 21
Incorrect syntax near 'dbname'.
What is wrong with my code?
DECLARE @name nvarchar(max), @stat nvarchar(max)
set @stat = N'update DBNAME.dbo.Ad
set Label = ''Special Ad'' where Label =''AdXXXX'''
DECLARE dbname CURSOR FOR select name from sys.databases where name like '%config%'
open dbname
begin try
while 1=1
begin
fetch next from dbname into @name
set @stat=REPLACE(@stat,'DBNAME',@name)
exec sp_executesql @stat
end
end try
close dbname
deallocate dbname
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
TRY
块后面必须紧跟着CATCH
块:A
TRY
block must be immediately followed by aCATCH
block:请使用以下 sql 游标 脚本
请注意,set @stat 声明语句已移至光标
因为在第一次替换后,原始的 @stat 发生了变化,并且您将无法再次更改它
Please use the following sql cursor script
Note that the set @stat declaration statement is moved into the cursor
Because after the first replace the original @stat changes and you'll not be able to alter it again
您有一个
TRY
块,但没有CATCH
块:请参阅
尝试...捕获
you have a
TRY
block without aCATCH
block:See the documentation on
TRY...CATCH