Sample Header Ad - 728x90

What are better approaches than loops for frequent operations?

3 votes
1 answer
290 views
I have to make multiple UPDATE statements, but I'm looking for the best approach to do so, in terms of readability and performance. I looked for another answers but the only thing I found is that *"Loops are bad and should be the last resource"*, so that's why I'm asking this question. Basically, I have a M:M table, with 'X' and 'Y' FKs and a BOOLEAN column which value is TRUE by default. In the table with the 'X' ID, I have another FK Column, let's name it Z. Now, I want to UPDATE the BOOLEAN value to FALSE in the M:M table, given certain 'Z' (Basically, only change rows where 'X' corresponds to a 'Z' value given by me). Consider that the same value for 'X' repeats several times in the table, with a variation in the 'Y' value. Of course, I can use a Cursor or a WHILE loop, but as I stated before, I'm not looking for the logic of this, but the best option specially in performance, considering it's going to be a frequent operation, and the volume of data is not little; I'm asking for alternatives, so I'll be sure to pick the best one for my case. ### Here's a detailed example ### ------------------------------ Given the following tables:
CREATE TABLE FirstExampleTable (
    Id INT IDENTITY(1,1) PRIMARY KEY,
	ForeignKey INT NOT NULL, -- There might be multiple rows with the same FK
	FOREIGN KEY (ForeignKey) REFERENCES SomeOtherTable(Id)
);

CREATE TABLE SecondExampleTable (
    Id INT IDENTITY(1,1) PRIMARY KEY
);

CREATE TABLE exampleTable (
    Id INT IDENTITY(1,1) PRIMARY KEY,
    FirstFK INT NOT NULL,
    SecondFK INT NOT NULL,
    ThisShouldBeFalse BIT DEFAULT 1 NOT NULL,
    FOREIGN KEY (FirstFK) REFERENCES FirstExampleTable(Id),
    FOREIGN KEY (SecondFK) REFERENCES SecondExampleTable(Id)
);
And the following data:
INSERT INTO FirstExampleTable VALUES
(1), -- ID 1
(2), -- ID 2
(1); -- ID 3

INSERT INTO exampleTable VALUES
(1, 1, 1),
(1, 2, 1),
(1, 3, 1),
(1, 4, 1),
(2, 1, 1),
(2, 2, 1),
(2, 3, 1),
(2, 5, 1),
(3, 3, 1),
(3, 4, 1);
Imagining I want to update all values to FALSE where the ID in exampleTables corresponds to a '1' FK, then it should end up like this:
(1, 1, 0)
(1, 2, 0)
(1, 3, 0)
(1, 4, 0)
(2, 1, 1)
(2, 2, 1)
(2, 3, 1)
(2, 5, 1)
(3, 3, 0)
(3, 4, 0)
Asked by Gabriel A. (31 rep)
Jun 6, 2025, 03:27 PM
Last activity: Jun 7, 2025, 11:17 AM