SQL INSERT数据基于另一个表的列

时间:2015-07-08 17:02:39

标签: sql sql-server sql-insert

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

Products列:

  • ProductID(PK)
  • ProductName

ProductKeys列:

  • ID(PK)
  • ProductKey
  • ProductID(FK)
  • Price

我正在尝试插入新的ProductKey

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

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

这当然有效。但是,如果我想根据产品名称插入新的ProductKey,并根据ProductID自动设置ProductName该怎么办。

我希望你理解我的问题。提前谢谢大家!欢呼声。

编辑:要在该表中插入,我必须为所有字段提供值,但如果我不知道ProductID的值并且我知道ProductName,那么我可以根据ProductName而不是ProductID插入ProductKey。

对不起那些乱七八糟的人来说,不熟悉SQL。

1 个答案:

答案 0 :(得分:1)

您可以根据表格数据选择要插入的数据,如下所示:

Insert into ProductKeys(ProductKey , ProductID , Price)
select p.productName, p.productId, 1 -- whatever your price is
from products p
where p.productName = 'testkey'
  先生,我可以问你,这可以延长吗?例如!如果ProductName不存在,则命令将无法正常工作。但是,如果ProductName不存在,还可以在Products表中插入带有所选ProductName的新产品,并创建ProductKey。可以用“不存在”来扩展吗?谢谢大家先生!你已经帮我了很多!

我认为你不能在一个声明中做到这一点 - 也许你可以在插入触发器之前使用on,但我认为类似的东西会因批量插入而崩溃。 (但不要引用我,从未尝试过)

然而,您可以将其分解为多个这样的语句:

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