Avoiding Loops in SQL, #temptables?

81 views Asked by At

I have heard/read people say that "loops are bad mkay" or "If you think you need a loop, you don't". I understand the processing and speed implications of running a loop on a database but are there exceptions to this rule? I am trying to resolve an issue where I need to, infrequently, insert 80 lines into a table all with the exact same information except for an ID field.

I have written two queries which in theory will do what I need but I would like to know if the query containing the loop should be avoided at all costs, if the #temptable method is sound, and if there is a better way to accomplish what I am trying to do outside of the two options I've presented. Thanks in advance.

For some background I have tableB which contains an ID field, the field being a FK to an ID field on TableA.

Query 1

DECLARE @minid as int = 1
DECLARE @maxid as int = 100
WHILE @minid <= @maxid
    BEGIN
    SET @minid = @maxid + 1
        IF NOT EXISTS (SELECT * FROM TableA WHERE eID = @minid AND Name = 'B')
        BEGIN
            INSERT INTO TableA (eID, B, C)
            VALUES
            (@minid, B, C)
        END
    IF @minid = @maxid BREAK
    END



Query 2

DROP TABLE IF EXISTS #TempTable

CREATE TABLE #TempTable
eID
B
C 

INSERT INTO #TempTable (eID)
SELECT eID
FROM TableB
WHERE (code to specify which eIDs to pull out of table b)

UPDATE #TempTable 
SET B = 'XX', C = 'XX'

INSERT INTO TableA (eID, B, C)
SELECT eID, B, C
FROM #TempTable
1

There are 1 answers

0
Charlieface On

They are both wrong. You don't need temp tables or loops. Just use GENERATE_SERIES to generate a bunch of rows.

INSERT INTO TableA
  (eID, B, C)
SELECT
  g.value,
  'XX',
  'XX'
FROM GENERATE_SERIES(1, 1000) AS g;

In older versions of SQL Server you can use one of Itzik Ben-Gan's numbers functions.