Sql Sever 表遍历,Exec动态执行sql语句返回变量

    DECLARE @id AS INT,
            @table_name AS NVARCHAR(200),
            @number_column_name AS NVARCHAR(200),
            @sql NVARCHAR(MAX),
            @cnt INT;

    WHILE EXISTS (SELECT id FROM @temp)
    BEGIN
        -- 也可以使用top 1
        SET ROWCOUNT 1;
        SELECT @id = id,
               @table_name = table_name,
               @number_column_name = number_column_name
        FROM @temp;
        SELECT @table_name = table_name,
               @number_column_name = number_column_name
        FROM dbo.sed_filing_doc
        WHERE id = @id;

        SET @sql
            = N' select @cnt=count(*)  from ' + @table_name + N'  where filing_id=' + CAST(@filing_id AS NVARCHAR(200));
        EXEC sp_executesql @sql, N'@cnt int out', @cnt OUT;

        UPDATE dbo.sed_filing_doc
        SET count = @cnt
        WHERE id = @id;
        SET ROWCOUNT 0;

        DELETE FROM @temp
        WHERE id = @id;
    END;


posted @ 2020-04-06 17:02  唯爱金生  阅读(280)  评论(0编辑  收藏  举报