简体   繁体   English

SQL Server,针对每条指令

[英]SQL Server, for each instruction

  1. Clients (Id, Name...) 客户(身份证,姓名......)
  2. Products (id, Name...) 产品(id,名称......)
  3. Clients_Products (client_id, product_id) 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. 我添加了10个客户端,我需要更新联接表(clients_products)并为每个产品和每个客户端添加一条新记录。

Is there any way to do a double loop or something in SQL Server management studio or something? 有没有办法在SQL Server管理工作室或其他东西做双循环或什么?

Then I deleted the 10 rows, but i want to create these 10 rows and join them with all products directly. 然后我删除了10行,但我想创建这10行并直接与所有产品连接。 (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. 我可以使用vb .net以编程方式执行此操作,但我认为有任何方法可以实现此目的。

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')

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

I'm not sure i understand what you are saying, but it sounds like you want to loop through a record set in SQL. 我不确定我理解你在说什么,但听起来你想要在SQL中循环记录集。 See this: 看到这个:

http://msdn.microsoft.com/en-us/library/ms180152.aspx 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM