如何在while循环中多次存储到临时表中?

时间:2011-10-06 17:42:57

标签: sql tsql

我正在做一个内连接,每次都会在我的表中附加一个新列

例如,我正在尝试这样做:

WHILE @Counter <= @MaxCount
BEGIN
    SELECT @ParameterDefinitionID = ParameterDefinitionID FROM #CachedParameterDefinitionIDs WHERE RowNumber = @Counter
    SELECT * INTO #ContactsWithPatientID FROM #ContactsWithPatientID INNER JOIN (SELECT Parameter2.ContactID AS 'Parameter2ContactID', Parameter2.Value AS FirstName FROM #CachedParameterValues Parameter2 WHERE ParameterDefinitionID = @ParameterDefinitionID) FirstNameTable ON #ContactsWithPatientID.ContactID = FirstNameTable.Parameter2ContactID
    SET @Counter = @Counter + 1
END

它在第一次迭代时不起作用,因为:

There is already an object named '#ContactsWithPatientID' in the database.

我怎样才能让它发挥作用?有没有其他方法可以做到这一点?我这样做是因为我需要在查询中附加一定数量的行作为列。

1 个答案:

答案 0 :(得分:6)

首先创建表格

CREATE TABLE #ContactsWithPatientID (...)
WHILE @Counter <= @MaxCount
BEGIN
    SELECT @ParameterDefinitionID = ParameterDefinitionID 
    FROM #CachedParameterDefinitionIDs
    WHERE RowNumber = @Counter

    INSERT #ContactsWithPatientID
    SELECT *
    FROM #ContactsWithPatientID 
            INNER JOIN 
            (SELECT Parameter2.ContactID AS 'Parameter2ContactID', Parameter2.Value AS FirstName 
            FROM #CachedParameterValues Parameter2 
            WHERE ParameterDefinitionID = @ParameterDefinitionID) FirstNameTable ON #ContactsWithPatientID.ContactID = FirstNameTable.Parameter2ContactID

    SET @Counter = @Counter + 1
END

这几乎肯定可以一次性完成作为递归CTE可能