Q:

SQL Server Cursor duplicates issue

Question about SQL-Server I have a Table that holds Id's 1 2 3 4 5 and I want to create a store procedure that performs an insert to another table by passing a parameter so essentially the result would like something like that
1   134
2   134
3   134
4   134
5   134
I know that there's away in by doing it with cursor.

DECLARE @LocationID Int -- @LocationID is what I'm passing to the store proc
DECLARE cursorName CURSOR -- Declare cursor

FOR
 
Select ModuleID FROM Modules 
Where  Active = 1
 
OPEN cursorName 

FETCH NEXT FROM cursorName 
 
   INTO @LocationID 
 

WHILE @@FETCH_STATUS = 0
 
BEGIN
 Insert INTO PostModules(LocationID,ModuleID) 
 Select @LocationID,ModuleID from Modules
 
   FETCH NEXT FROM cursorName
 
   INTO @LocationID
 


END
 
CLOSE cursorName -- close the cursor

DEALLOCATE cursorName -- Deallocate the cursor

I'm getting too many results in theory I'm only supposed to get:
Modules Table contains 5 Id's
@LocationID = 134 -- Been passed in to the store procedure
Results:
1 134  | 2 134 | 3 134 | 4 134 | 5 134

A:

As has been said already, you don't need a cursor to achieve this. Set-based operations are always faster than approaching a dataset by doing a row-by-row operation.
Here's an update statement that will achieve the desired result:
UPDATE 
    PostModules
SET 
    LocationID = 123
WHERE 
    EXISTS (
        SELECT 1 FROM Modules b WHERE ACTIVE = 1 AND PostModules.ModuleID = b.id)

Here's some sample code that creates the tables and fills them with sample data:
CREATE TABLE Modules (id int, active bit)

INSERT INTO Modules VALUES (1,1), (2,1), (3,1), (4, 1), (5, 1), (6, 0), (7, 0), (8, 1);

Notice that 1-5 as well as 8 are active, but 6 and 7 are not.
CREATE TABLE PostModules(LocationID int ,ModuleID int);

INSERT INTO PostModules Values 
(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8);

I'm adding a default value for every ModuleID here. If there's no matching moduleID, nothing will happen. 
UPDATE PostModules
SET LocationID = 123
WHERE EXISTS (SELECT 1 FROM Modules b WHERE ACTIVE = 1 AND PostModules.ModuleID = b.id)

SELECT * FROM PostModules

Output:
LocationID  ModuleID
123 1
123 2
123 3
123 4
123 5
0   6
0   7
123 8

Keep in mind that in order for this to work, PostModules already has to have a value for every active ModuleID. If you have the above script, you can verify this by adding ModuleID 9:
INSERT INTO Modules VALUES (9,1)

Rerunning the UPDATE statement will yield the exact same results as before, because 9 doesn't exist as a ModuleID in the PostModules table.
In theory, your code actually ought to work as well. I'm not sure why you would be seeing 5 results. If you are still curious, please show us the actual results returned by the cursor.

