I'm doing an inner join that appends a new column to my table every time it
For example, I'm trying to do this:
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
It doesn't work on the first iteration because:
There is already an object named '#ContactsWithPatientID' in the database.
How can I make it work? Is there some alternative way to do this? I am doing it this way because I need to append a certain number of rows as columns in my query.
Create the table first
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
This can almost certainly be done in one go too as a recursive CTE probably
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With