SELECT then INSERT data in a matrix way
-
Hi, I have a question regarding SQL queries. In my select statement in my stored procedure I will receive a table of information like this: UserId ------ 2 4 5 After this select statement I'd like to add a insert statement to add records For each of these UserIds (as UserIdFrom) with the other ones (as UserIdTo) I want to Insert into a table information like following: UserIdFrom UserIdTo ---------- -------- 2 4 2 5 4 2 4 5 5 2 5 4 I would be grateful if someone help me Smile | :) SELECT UserId FROM Users INSERT INTO myTable (UserIdFrom, UserIdTo) VALUES (@UserIdFrom, @UserIdTo)
-
Hi, I have a question regarding SQL queries. In my select statement in my stored procedure I will receive a table of information like this: UserId ------ 2 4 5 After this select statement I'd like to add a insert statement to add records For each of these UserIds (as UserIdFrom) with the other ones (as UserIdTo) I want to Insert into a table information like following: UserIdFrom UserIdTo ---------- -------- 2 4 2 5 4 2 4 5 5 2 5 4 I would be grateful if someone help me Smile | :) SELECT UserId FROM Users INSERT INTO myTable (UserIdFrom, UserIdTo) VALUES (@UserIdFrom, @UserIdTo)
Try something like this:
INSERT INTO myTable
(
UserIdFrom,
UserIdTo
)
SELECT
F.UserId,
T.UserId
FROM
Users As F
CROSS JOIN Users As T
WHERE
T.UserId != F.UserId
;
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
Try something like this:
INSERT INTO myTable
(
UserIdFrom,
UserIdTo
)
SELECT
F.UserId,
T.UserId
FROM
Users As F
CROSS JOIN Users As T
WHERE
T.UserId != F.UserId
;
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
thank u it helped me a lot! :)