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;