2012-08-01 108 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表中