Thursday, August 5, 2010

MS SQL Query - Loop question

Programmer Question

I'm trying to create a query that would generate a cross-check table with about 40 custom columns that show Y or N. Right now I have



SELECT DISTINCT [Company],
[Option1],
[Option2],
[Option3],
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 1 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 2 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
CASE
WHEN [Table1].[ID1] IN (SELECT ID2 FROM Table2 WHERE Variable = 3 AND Bit = 1) THEN
'Y'
ELSE 'N'
END AS 'CustomColumn1:',
.............
-- REPEAT ANOTHER 40 times
FROM [Table1]
WHERE [Table1].[OtherCondition] = 'True'
ORDER BY [Company]


So my question is, how do I create a loop (while? for?) that will loop on Variable and assign Y or N to the row based on the condition, rather than creating 40+ Case statements?



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails