SQL INSERT data based on a column of another table

SQL INSERT data based on a column of another table

我在数据库中有两个 table,ProductsProductKeys

Products 列:

ProductKeys 列:

我正在尝试插入一个新的 ProductKey

假设我有一个产品 ProductID = 1ProductName = 'test'

Insert into ProductKeys(ProductKey, ProductID, Price)
    select 'testkey', 1, 4

这当然有效。但是,如果我想根据产品名称插入新的 ProductKey 并根据 ProductName.

自动设置 ProductID 怎么办?

希望您理解我的问题。提前谢谢大家!干杯。

编辑:要插入 table 我必须为所有字段提供一个值,但是如果我不知道 ProductID 的值但我知道 ProductName 怎么办,所以我可以插入一个 ProductKey 基于ProductName 而不是 ProductID。

SQL.

的新手,麻烦大家了

您可以 select 数据根据 table 的数据插入,如下所示:

Insert into ProductKeys(ProductKey , ProductID , Price)
select p.productName, p.productId, 1 -- whatever your price is
from products p
where p.productName = 'testkey'

Sir, can I ask you , can this be extended? for example! If the ProductName does not exist the command won't work for sure. But if in case when ProductName does not exist ALSO insert a NEW product in Products table with the selected ProductName and also create the ProductKey. Can it be extended with a 'not exist'? Thanks a bunch sir! You already helped me alot!

我认为您不能在单个语句中执行此操作 - 也许您可以使用 on before insert 触发器,但我认为类似的事情会因批量插入而崩溃。 (但不要引用我的话,从未尝试过)

然而,您可以将其分解为多个语句,如下所示:

declare @productName varchar(50), @productId int, @price int

select 
        @productName = 'someNameThatDoesntExist', 
        @price = 5 -- whatever your price is.

if not exists (     -- check if the product name exists in the products table, if not create it
    select 1 
    from products 
    where productName = @productName
)
    begin
        insert into products (productName)
        select @productName

        select @productId = @@identity
    end
else -- the product already exists in the products table, so lookup its ID
    select @productId = productId
    from products
    where productName = @productName

Insert into ProductKeys(ProductKey , ProductID , Price)
select @productName, @productId, @price