使用MS SQL Server和Terdata避免使用While或Cursor?

时间:2016-03-15 20:11:39

标签: sql while-loop cursor teradata

我有一个非常大的表,我们最近为新报告添加了两列。问题是我们必须返回并从Teradata中提取原始数据以更新每个当前列。在编写while语句或游标时,这并不算太糟糕,但是作业的性能和速度非常慢。我曾经在这里找到过一次,现在我想避免这种情况。

是否有任何建议可以加快Teradata的拉动并更新我们的本地表?

SELECT ROW_NUMBER() OVER (ORDER BY var4) AS ROW, * INTO #updateData FROM TBL_UPDATE_ME
WHERE var4 IS NOT NULL AND col1 IS NULL

DECLARE @TERADATA table (col1 VARCHAR(10) , col2 NVARCHAR(10))

DECLARE
@QUERY VARCHAR(MAX),
@row int = 1,
@DATE nvarchar(10),
@TIME NVARCHAR(8),
@code NVARCHAR(8),
@var3 NVARCHAR(8),
@var4 NVARCHAR(20),
@var2 NVARCHAR(10)

while @row <= (select MAX(row) from #updatedata)
begin

    SELECT @DATE = (SELECT date FROM #updatedata where ROW = @row)
    SELECT @TIME = (SELECT time FROM #updatedata where ROW = @row)
    SELECT @code = (SELECT code FROM #updatedata where ROW = @row)
    SELECT @var3 = (SELECT var3 FROM #updatedata where ROW = @row)
    SELECT @var4 = (SELECT var4 FROM #updatedata where ROW = @row)
    SELECT @var2 = (SELECT var2 FROM #updatedata where ROW = @row)


    SET @QUERY = 
    '
        SELECT col1, col2
        FROM OPENQUERY (AAAAAAA_TERADATA,''
        SELECT
        TRIM(LEADING '''' '''' FROM (TRIM (TRAILING '''' '''' FROM a.col1))) AS col1,
        TRIM(LEADING '''' '''' FROM (TRIM (TRAILING '''' '''' FROM a.col2))) AS col2
        FROM WWWWWW.WWWWWW as a
        left join TTTTT.TTTTas b
        on a.var1 = b.var1
        WHERE
        (
            B.var4 = '''''+@var4+'''''
            AND B.var2 = '''''+@var2+'''''
            AND B.var3 = '''''+@var3+'''''
            AND B.code = '''''+@code+'''''
            AND B.time = '''''+@TIME+'''''
            AND B.date = '''''+@DATE+'''''
        )

        '')
    '
    INSERT INTO @TERADATA
    EXEC(@QUERY)

set @row = @row + 1
end

update a
set a.col1 = b.col1 , a.col2 = b.col2
from TBL_UPDATE_ME as a, @TERADATA as b

drop table #updateData

0 个答案:

没有答案