码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2020-04-06 17:53:51      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:pre   number   nvarchar   upd   declare   row   --   exists   ble   

    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;


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

标签:pre   number   nvarchar   upd   declare   row   --   exists   ble   

原文地址:https://www.cnblogs.com/dreamsails/p/12642857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!