我的问题与EXEC
一致,除了为@counter
增加价值外,所有工作都有效。
如果我执行类似下面的内容,则没有问题:
EXEC('if exists(select * from '+ @table + ' where ' + @column + ' = ' + @someValue + ') print ''test''');
如何为@counter
增加价值?当我在代码下面运行时,我收到错误:
0附近的语法不正确。
CREATE PROCEDURE testSP
AS
BEGIN
DECLARE testCursor CURSOR;
DECLARE @table NVARCHAR;
DECLARE @column NVARCHAR;
DECLARE @someValue NVARCHAR;
...
BEGIN
DECLARE testCursor2 CURSOR;
DECLARE @counter INT = 0;
...
BEGIN
DECLARE @result INT = 0;
EXEC( 'if exists(select * from '+ @table + ' where ' + @column + ' = ' + @someValue + ') set ' + @counter + '=1' );
IF (@counter > 0)
PRINT 'test';
...
END
...
END
END
go
答案 0 :(得分:3)
你可以使用它。
CREATE PROCEDURE testSP
AS
BEGIN
DECLARE testCursor CURSOR;
DECLARE @table NVARCHAR;
DECLARE @column NVARCHAR;
DECLARE @someValue NVARCHAR;
...
BEGIN
DECLARE testCursor2 CURSOR;
DECLARE @counter INT = 0;
...
BEGIN
DECLARE @result INT = 0;
declare @sqlText nvarchar(max)= N'if exists(select * from '+ @table + ' where ' + @column + ' = ' + @someValue + ') SET @counter = 1'
DECLARE @ParmDefinition nvarchar(500) = N'@counter INT OUTPUT';
EXEC sp_executesql @sqlText, @ParmDefinition, @counter = @counter OUTPUT ;
if(@counter>0)
print 'test';
...
END
...
END
END