循环遍历存储过程中的记录集

时间:2017-11-10 12:27:11

标签: sql tsql

我创建了一个将SELECT语句作为值(fieldname sqltxt)的tbl。

现在想逐个读取行并执行存储在该表中的所有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中 它返回超过10,00,000条记录 现在想在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记录集。

DOCID SQLTXT

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

1 个答案:

答案 0 :(得分:0)

我无法在这里解决实际问题,但我可以详细说明如何遍历所有记录的问题。顺便说一句&LT;循环对性能很糟糕,因此在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