且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果两个表相互依赖,如何使用两个查询在两个表(产品,颜色)中插入数据

更新时间:2023-11-29 19:25:04

有几种方法可以做到这一点. 1.是通过使用存储过程来完成的,因为您并未真正提供有关正在执行哪种类型的插入的大量数据.我假设您的主键是identity类型(自动生成).因此,Im使用@@identity系统功能从产品表中返回最后插入的ID..
There are several ways of doing this..
1. is by the use of a stored procedure and since you didnt really provide much data on what type of insert you are doing. I assumed your primary keys were identity types (auto-generate). so Im using the @@identity system function to return the last inserted id from your product table..
create procedure sp_insertData
@prod_name varchar(100),
@prod_type varchar(50),
@color_name varchar(50)
as
begin
   insert into products(name,type)
   values( @prod_name,
           @prod_type
         )

   declare @id int
   select @id = @@identity

   insert into color(prod_id, color)
   values(@id,
          @color_name
         )
end



2.您还可以使用Triggers ..,这样就必须在第二个表上设置外键约束以引用第一个表.然后,触发器将根据您要插入的内容自动将您添加到第二张表中.



2. You could also use Triggers..and in this way you would have to set a foreign key constraint on your second table to reference the first table. A trigger would then automatically do your addition to your second table based on what you want to insert.


所以我不清楚您一次要插入哪个对象

但是我认为在查询中您可以通过使用``;''分隔每个插入查询来传递两个插入查询,您可以一次插入.
So I am not clearly understanding by which you want to insert at once

But I think in the Query you can pass both insert query by separating each using '';'', You can insert at once.