在动态SQL中使用@@ ROWCOUNT

时间:2013-10-29 13:08:04

标签: sql-server sql-server-2008 tsql dynamic-sql rowcount

我正在使用Dynamic SQL从多个表中检索数据集,以便监控从iSeries系统中提取的每日数据。

我有下面的动态SQL代码可以正常工作,但我想只运行数据来获取每个表记录,如果当天提取了数据

-- Create a table variable to store user data
DECLARE @myTable TABLE
(
    docID INT IDENTITY(1,1),
    docRef VARCHAR(50),
    letterDir VARCHAR(500)
);

insert @myTable select docRef, saveDir from alpsMaster.dbo.uConfigData

-- Get the number of rows in the looping table
DECLARE @RowCount INT, @SQL nvarchar(500), @LoopSQL nvarchar(2000), @Date varchar(20)

set @Date='29 Oct 2013'
SET @RowCount = (SELECT COUNT(docID) FROM @myTable) 

-- Declare an iterator
DECLARE @I INT

-- Initialize the iterator
SET @I = 1

-- Loop through the rows of a table @myTable
WHILE (@I <= @RowCount)
    BEGIN
    -- Declare variables to hold the data which we get after looping each record

    DECLARE @docRef VARCHAR(10), @saveDir VARCHAR(500)

    -- Get the data from table and set to variables
    SELECT @docRef = docref FROM @myTable WHERE docID = @I
    SELECT @saveDir = letterDir FROM @myTable WHERE docID = @I

    -- Display the looped data
    --PRINT 'Row No = ' + CONVERT(VARCHAR(2), @I) + '; docRef = ' + @docRef 

select @LoopSQL='
use alpsProduction;
declare @SQL nvarchar(500);

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(''[dbo].['+@docRef+']''))
    begin

    if exists(select * from sys.columns 
        where Name = ''YPTMPID'' and Object_ID = OBJECT_ID(''[dbo].['+@docRef+']''))
        begin

            set @SQL=''SELECT t.template_name,'''''+@saveDir+''''', Y.* 
             FROM [alpsProduction].[dbo].'+@docRef+' Y, alpsMaster.dbo.uDocumentTemplates t 
                where DTEINP='''''+@Date+''''' and t.template_Id=y.YPTMPID and t.docRef='''''+@docRef+'''''''


            exec sp_executesql @SQL

            end
    end
    '
    --print @LoopSQL
    exec sp_executesql @LoopSQL

    -- Increment the iterator
    SET @I = @I  + 1
END

所以我尝试使用

IF @@ROWCOUNT >0 
    Begin
        exec sp_executesql @SQL
    end

但似乎永远不会填充@@ Rowcount。

如果当前表(由exec sp_executesql @SQL标识)在今天的日期中有记录(格式为dd mmm yyyy)@docRef)的最佳方式是什么? >

1 个答案:

答案 0 :(得分:1)

创建作业以执行sql脚本,其中你必须在当天检查插入的数据然后执行你的sp。像这样。

IF EXISTS ( SELECT * FROM @TABLE T WHERE DATEDIFF(DD, GETUTCDATE(), T.CREATEDON) = 0 )
BEGIN
     EXEC SP_EXECUTESQL @SQL
END