如何在游标内的动态查询中为参数赋值

时间:2018-01-30 05:53:24

标签: sql tsql sql-server-2012

我的问题与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

1 个答案:

答案 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