开发者

SQL Server, for each instruction

开发者 https://www.devze.com 2023-01-26 14:07 出处:网络
Clients (Id, Name...) Products (id, Name...) Clients_Products (client_id, product_id) I added 10 Clients and i need to update the join table (clients_products) and add a new record for each produc
  1. Clients (Id, Name...)
  2. Products (id, Name...)
  3. Clients_Products (client_id, product_id)

I added 10 Clients and i need to update the join table (clients_products) and add a new record for each product and each client.

Is there any way to do a double loop or something in SQL Server management studio or something?

Then I deleted the 10 rows, but i want to create these 10 rows and join them with 开发者_Python百科all products directly. (please reword this last sentence - makes no sense)

any help? thx

i can do this programmatically with vb .net but i think that there would be any way to achieve this.


This calls for a cross join

INSERT INTO clients_products (client_id, product_id)
SELECT c.ID, p.ID
FROM Clients c
CROSS JOIN Products p
LEFT JOIN clients_products cp
    on c.client_id and p.product_id
WHERE cp.client_id is null and p.product_id is null


INSERT INTO Clients_Products
SELECT c.Id, p.Id
FROM Clients c
JOIN Products p on 1=1
WHERE c.Name in ('NEW CLIENT 1', 'NEW CLIENT 2')


I'm not sure i understand what you are saying, but it sounds like you want to loop through a record set in SQL. See this:

http://msdn.microsoft.com/en-us/library/ms180152.aspx


If i understood your question correctly, you are asking for a Cartesian join of both the table:

insert into clients_products  
select
  clients.id,products.id 
from clients
  cross join products
0

精彩评论

暂无评论...
验证码 换一张
取 消