使用select查询插入表中

时间:2016-03-21 18:44:15

标签: sql sql-server-2008 loops stored-procedures

我有一个返回n条记录的select查询。我希望那些用不同的B_ID插入到同一个表中我的B_ID将是(4,51,16,7)我如何编写简单的查询。我可以通过for循环来做到这一点。但我想要一些更简单和优化的查询 隐藏复制代码

INsert into S_FACT(S_ID,B_ID,G_ID,AMOUNT)
  (select '150',B_ID,G_ID,AMOUNT from S_FACT where S_ID=2 and  B_ID =(2))

我的清单就像这样(4,7,22,55)

    INsert into S_FACT(S_ID,B_ID,G_ID,AMOUNT)
      (select '150','4',G_ID,AMOUNT from S_FACT where S_ID=2 and  B_ID =(2))  
      INsert into S_FACT(S_ID,B_ID,G_ID,AMOUNT)
      (select '150','7',G_ID,AMOUNT from S_FACT where S_ID=2 and  B_ID =(2))          
    INsert into S_FACT(S_ID,B_ID,G_ID,AMOUNT)
      (select '150',22',G_ID,AMOUNT from S_FACT where S_ID=2 and  B_ID =(2))
  INsert into S_FACT(S_ID,B_ID,G_ID,AMOUNT)
      (select '150',55',G_ID,AMOUNT from S_FACT where S_ID=2 and  B_ID =(2))

等取决于列表

1 个答案:

答案 0 :(得分:0)

  

我有一个返回n条记录的选择查询

您应该在问题文本中 提供 您的选择。

你可以:

insert into S_FACT( S_ID, B_ID, G_ID, AMOUNT)
select '150', sq.b_id, s.G_ID, s.AMOUNT 
from S_FACT s
cross join (
    -- Substitute here Whatever your select query is, selecting only the b_id
    select 4 as b_id
    union all select 51
    union all select 16
    union all select 7
) sq
where s.S_ID=2 and s.B_ID = 2