2012-08-01 104 views
39

我有一些需要插入到多个表中的记录。每隔一列将是一个常数。对选取的每一行执行插入操作?

下面可怜的伪代码 - 这就是我想做的事:

create table #temp_buildings 
(
    building_id varchar(20) 
) 
insert into #temp_buildings (building_id) VALUES ('11070') 
insert into #temp_buildings (building_id) VALUES ('11071') 
insert into #temp_buildings (building_id) VALUES ('20570') 
insert into #temp_buildings (building_id) VALUES ('21570') 
insert into #temp_buildings (building_id) VALUES ('22570') 

insert into property.portfolio_property_xref 
     (portfolio_id , 
      building_id , 
      created_date , 
      last_modified_date 
     ) 
values 
     ( 
      34 , 
      (
       select building_id 
       from #temp_buildings 
      ) , 
      getdate() , 
      null 
     ) 

意图:执行插入到property.portfolio_property_xref对#temp_buildings每个记录

我想我能做到这与一个光标 - 但相信这将是非常缓慢。由于这个练习将来可以重复,我宁愿用更快的方法解决这个问题,但我不确定如何。对于任何反馈,我们都表示感谢!

+1

提示:您也可以使用'insert into #temp_buildings(building_id)VALUES('11070'),('11071')...插入多行。 – HABO 2012-08-01 02:35:35

+0

@Habo不错的一个 - 刚刚砍掉我的脚本的50行:)谢谢你 – Codingo 2012-08-01 03:04:59

回答

88
INSERT INTO table1 (column1) 
SELECT col1 
FROM table2 

像:

insert into property.portfolio_property_xref 
( 
    portfolio_id , 
    building_id , 
    created_date , 
    last_modified_date 
) 
select 
    34, 
    building_id, 
    getdate(), 
    null 
from 
    #temp_buildings 
+5

Eck。我很尴尬,如果这是这么简单:) – Codingo 2012-08-01 00:41:49

+22

永远不会知道,直到你问,对吧? – 2012-08-01 00:48:22

0

试试这个

insert into property.portfolio_property_xref 
    ( 
     portfolio_id , 
     building_id , 
     created_date , 
     last_modified_date 
    ) 
    Select 
     34, 
     building_id, 
     GETDATE(), 
     NULL 
    From #temp_buildings 
3

你会希望使用INSERT INTO SELECT FROM(见SQL Fiddle with Demo

insert into property.portfolio_property_xref 
( 
    portfolio_id , 
    building_id , 
    created_date , 
    last_modified_date 
) 
SELECT 34 , 
     building_id, 
     getdate(), 
     null 
from #temp_buildings 
0

你是说,你能做到这一点用游标。正如其他答案显示你,你不必这样做。 SQL Server是一个基于集合的RDMS,它更能够处理一组数据,然后处理单行数据。

1

一种随机的,但我觉得这可能对任何人来这里的这个问题有用。有时,我使用Microsoft Excel VBA生成上面列出的部分SQL语句。当我在进行表格构建和数据转换以创建新工作的情况下,我发现这非常有用。这是一个非常简单的例子。它创建了两个不相关系统之间的链接。然后,该链接允许我在仓库环境中构建一个将3个不相关的系统捆绑在一起的新表。无论如何,它允许我在几秒钟内创建大于5000行的SQL(一次性使用 - 以及更大的ETL任务的一小部分)。

Option Explicit 

Dim arow As Integer 
Dim acol As Integer 
Dim lrow As Integer 
Dim IsCellEmpty As String 
Dim CustNo As Integer 
Dim SkuLevel As Integer 


Sub SkuLevelUpdate() 

'find end ouf input file 
arow = 1 
acol = 1 

Do 
    IsCellEmpty = Cells(arow, acol).Value 
    arow = arow + 1 
Loop Until IsCellEmpty = "" 

lrow = arow - 1 

'Write SQL 
arow = 2 
acol = 5 

Do 
    CustNo = Cells(arow, 1) 
    SkuLevel = Cells(arow, 4) 
    Cells(arow, acol) = "INSERT INTO dbo.#TempSkuLevelRelationships (CustNo, SkuLevel) VALUES (" & CustNo & ", " & SkuLevel & ");" 
    arow = arow + 1 
Loop Until arow = lrow 

End Sub 

是的,我知道所有关于SQL注入等创建电子表格(S),我复制/粘贴数据到新的建筑,表的修改,而当数据做类似大SQL代码当前未驻留在SQL表中