I want to loop a array of chars in a WHILE loop (with only two values : 'C' & 'P') and use this variable in a SQL statement.
PSEUDO CODE:
WHILE SELECT 'C' UNION SELECT 'P'
BEGIN
SELECT @Var -- Do real sql-statement here
END
I've this working code, but I was wondering if this can be written better / easier / more elegantly ?
DECLARE @Var CHAR(1)
DECLARE @counter INT
SET @counter = 0
WHILE @counter < 2
BEGIN
SELECT @Var =
CASE @counter
WHEN 0 THEN 'C'
ELSE 'P'
END
SELECT @Var -- Do real sql-statement here
SET @counter = @counter + 1
END
To clarify, the real sql-statement is something like:
INSERT INTO MyTable
SELECT A, B, @Var FROM AnotherTable WHERE ExportStatus = 'F'
real sqlthat you are trying to do. Generally you should be able to avoid loops, but not always. If this really does require a loop, what you have is fine. Or, you could consider aFAST_FORWARD READONLY Cursorand loop through your input data with that.