在存储过程中循环记录集



我创建了一个以SELECT语句为值的tbl(字段名sqltxt)。

现在,希望逐个读取行,并执行存储在该表中的所有select语句。

如果没有返回任何行,即零行

在DMSResults中插入一条新记录,其值为DMSRec中的DOCID为此,我使用以下脚本

set nocount on
use TESTDB
declare @sqlTXT as varchar(max);
DECLARE @DocID nvarchar(30);
drop table DMSResults
CREATE TABLE DMSResults  (DOCID  nvarchar(30) );`
drop table DMSRec

SELECT .....转换为DMSRec FROM tbl....

上面的语法是一个用于创建记录集的Big SQl脚本
对于我的运输,我将所有记录插入新的tbl中
它返回超过100000条记录现在想要在tbl DMSREC中循环,读取字段sqltxt的值执行该语句。

如果没有返回记录在DMSResults中插入一条值为DOCID字段的记录。

我也尝试了以下命令,但不知道如何在sql中循环以进行下一次rec,直到eof并退出

由于DMSRec是一个临时表,一旦处理了一行,我们就可以从DMSRec中删除记录。

declare @rc as  bigint
Select @rc = Row_Count
From sys.dm_db_partition_stats
Where Object_Name(Object_Id) = 'DMSRec'
WHILE @rc <1 
BEGIN 
exec(select sqltxt from dmsrec where row=1)
--          here check record is exist or not then 
--          if it is not exist or returning zero 
--          add record in dmsresult with docid value
--          delete dmsrec where row=1  
--          loop for next 
END

考虑到数据库SQL Server 2008r2的巨大规模,请指导我任何优化解决方案

DMSRec TBL记录集。

DOCIDSQLTXT

A01/17-18从TBL_LET中选择VRNO,其中VRNO='A01/17-18'

我不能在这里解决实际问题,但我可以详细说明如何循环所有记录的问题。BTW<循环对性能来说非常糟糕,因此在SQL Server中可以不惜一切代价避免循环。

--get the row count of the table
declare @rc as  bigint
Select @rc = (select count(*) from DMSRec)
--variables for incrementing rows and storing SQL
declare @i bigint = 1
declare @sql varchar(max)
WHILE @i <= @rc 
BEGIN 
--get the SQL Statement from the table
set @sql = (select sqltxt from dmsrec where row=@i)
--If no value was returned, insert into DSMResults
if (@sql is null) or (ltrim(rtrim(@sql)) = '')
begin
insert into DMSResults 
select DOCID from dmsrec
end
--If a value was returned, execute that statement
else
begin
exec(@sql)
end
--increment the row number
set @i = @i + 1
END

最新更新