0

我正在使用动态 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表(由@docRef

4

1 回答 1

1

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

IF EXISTS ( SELECT * FROM @TABLE T WHERE DATEDIFF(DD, GETUTCDATE(), T.CREATEDON) = 0 )
BEGIN
     EXEC SP_EXECUTESQL @SQL
END
于 2013-10-31T11:06:36.093 回答