0

I am trying to insert select query result into a temporary table inside the while loop. But below query gives me this error:

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

DECLARE @V_START INT = 1;
DROP TABLE #TT

WHILE(@V_START < 4)
BEGIN
    SELECT * INTO #TT
    FROM Table
    WHERE Column = @V_START;

    SET @V_START = @V_START + 10;
END

SELECT * FROM #TT
2
  • Which dbms are you using? (The above code is product specific.) Commented Jan 4, 2023 at 12:37
  • im using sql server Commented Jan 4, 2023 at 12:39

1 Answer 1

1

every time your loop is executed a temporary table will create, but first-time execution the temp table does not exist command run successfully and you give the error in the second round of loop execution. You can try it like below :

DECLARE @V_START INT = 1;
DROP TABLE IF EXISTS #TT;
CREATE TABLE #TT 
(
    --your columns
)

WHILE(@V_START < 40)
BEGIN
    INSERT INTO #TT
    (
        --your columns
    )
    SELECT --your columns
    FROM Table
    WHERE Column = @V_START;

    SET @V_START = @V_START + 10;
END

SELECT * FROM #TT

but better solution is using select into with condition for inserting data to temp table:

DROP TABLE IF EXISTS #TT

 SELECT * INTO #TT
    FROM Table
    WHERE Column % 10 = 0 AND Id < 10

    SELECT * FROM #TT
Sign up to request clarification or add additional context in comments.

1 Comment

I tried creating temp table. But while executing the procedure. Its just loading. Does not return result.

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.