TSQL迭代表并执行子查询

时间:2014-10-09 14:07:54

标签: sql sql-server-2008 tsql

在我的情况下,使用openquery的连接执行得非常糟糕,迭代本地表并按顺序执行子查询可能会更快,但我不知道这样做的合适方法。到目前为止,我的尝试是:

BEGIN
    CREATE TABLE #tmp
    (
        PayrollNo varchar(17)
    );
END 
GO

while(select InternalNo from [BUS].[dbo].[employees]) is not null
begin
    insert into #tmp select PayrollNo from openquery(CS, 'SELECT PD.PayrollNo FROM Payroll PD WHERE InternalNumber = ''' + InternalNo + '') OQ
end

因此,迭代一个包含员工的本地表,然后根据每个相关的内部编号选择每个工资单号。

1 个答案:

答案 0 :(得分:1)

您确定JOIN对性能有如此大的影响吗?好吧,如果你想尝试迭代表的值,那么你可以使用游标:

DECLARE @InternalNo INT -- Use the correct data type
DECLARE @Query VARCHAR(MAX);

DECLARE CC CURSOR FOR
SELECT InternalNo 
FROM [BUS].[dbo].[employees]

OPEN CC
FETCH NEXT FROM CC INTO @InternalNo
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Query = '  SELECT PayrollNo
                    FROM OPENQUERY( CS, 
                                    ''SELECT PD.PayrollNo 
                                      FROM Payroll PD 
                                      WHERE InternalNumber = ' + CAST(@InternalNo AS VARCHAR(10)) + ''') OQ'

    INSERT INTO #tmp
    EXEC(@Query)

    FETCH NEXT FROM CC INTO @InternalNo
END
CLOSE CC
DEALLOCATE CC

您可以测试这两个选项并选择哪个更好。