2

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'
1
  • 2
    It really does depend on the real sql that 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 a FAST_FORWARD READONLY Cursor and loop through your input data with that. Commented Feb 4, 2012 at 9:27

2 Answers 2

2

Simply use:

INSERT INTO MyTable
    SELECT * FROM AnotherTable WHERE ExportStatus 
        IN (SELECT 'C' UNION ALL SELECT 'P')
Sign up to request clarification or add additional context in comments.

Comments

0

Just insert it into the table.

Set operation perform better in SQL and A array can be placed into a table and operation can be performed on the table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.