我有这个查询,可以帮助我选择具有空值的列名。我想做的是仅更新第一列的值。我试图在更新查询后添加一个break语句以退出游标的while循环,但出现此错误
无法使用BREAK
语句超出范围
WHILE
语句。
这是我尝试过的代码
AS
declare @col varchar(255), @cmd varchar(max)
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'Grilles_de_tailles' and c.name like 'T%'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT TOP 1 * FROM Grilles_de_tailles WHERE [' + @col + '] IS NOT NULL and Code_Grille_BW = '+@codegrillebw+') begin
update Grilles_de_tailles set ['+@col+'] = '+@libtaille+' where Code_Grille_BW = '+@codegrillebw+'
break
end'
EXEC(@cmd)
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
我也尝试过这种方式
AS
declare @col varchar(255), @cmd varchar(max), @breakval numeric
SET @breakval=0
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'Grilles_de_tailles' and c.name like 'T%'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0 AND @breakval=0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT TOP 1 * FROM Grilles_de_tailles WHERE [' + @col + '] IS NOT NULL and Code_Grille_BW = '+@codegrillebw+') begin
update Grilles_de_tailles set ['+@col+'] = '+@libtaille+' where Code_Grille_BW = '+@codegrillebw+'
set '+@breakval+' = '+1+'
end'
EXEC(@cmd)
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo
这样,它甚至都不会进入while循环
我尝试使用GOTO,这是代码
DECLARE getinfo cursor
for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'Grilles_de_tailles' and c.name like 'T%'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
IF NOT EXISTS (SELECT TOP 1 * FROM Grilles_de_tailles WHERE @col IS NOT NULL
and Code_Grille_BW = '2456')
BEGIN
print ('aaaa')
update Grilles_de_tailles set @col = 'M'
GOTO Branch_one
END
FETCH NEXT FROM getinfo into @col
END
Branch_one:
CLOSE getinfo
DEALLOCATE getinfo ```
nothing happened I got "Commands completed successfully" but it seems that it didn't execute the instructions between BEGIN .. END since the print didn't work
答案 0 :(得分:0)
示例:
declare @col varchar(255), @cmd varchar(max)
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'Grilles_de_tailles' and c.name like 'T%'
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
declare @Break bit=0
SELECT @cmd = 'IF NOT EXISTS (SELECT TOP 1 * FROM Grilles_de_tailles WHERE [' + @col + '] IS NOT NULL and Code_Grille_BW = '+@codegrillebw+') begin
update Grilles_de_tailles set ['+@col+'] = '+@libtaille+' where Code_Grille_BW = '+@codegrillebw+'
SET @Break=1
end'
exec sp_executesql @cmd,'@Break bit OUTPUT',@Break OUTPUT
IF @Break=1
break
FETCH NEXT FROM getinfo into @col
END
CLOSE getinfo
DEALLOCATE getinfo