Question

I have 3 tables called: TableA, TableB, TPopulate

The tables: A,B have some rows i need to populare the table (TPopulate) without a Stored Procedure for Example PSEUDOCODE:

@loop1 = 1;
@loop2 = 1;
WHILE loop1 <= (Select COUNT(*) FROM TableA)
    WHILE loop2 <= (Select COUNT(*) FROM TableB)
        INSERT INTO TPopulate (column1, column2) VALUES (TableA.column1, TableB.column1)
    END;
END;

TableA Represent (users)
TableB Represent (Privileges)
TPopulate Represent (Users_Privileges)

What I try to do is insert all privileges to all existing users.

Was it helpful?

Solution

You don't need to use loops at all. You should be thinking in terms of SETS when using a relational database.

Here is the correct way to achieve this. First using the CROSS JOIN to create a cartesian set of all the combinations of ids from tableA and tableB. Then inserting that entire set into TPopulate

INSERT INTO TPopulate (column1, column2)
SELECT  T1.PKField
        ,T2.PKField
FROM    TableA T1
CROSS JOIN
        TableB T2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top