2016-03-08 152 views
0

我知道這個問題可能聽起來像一個重複的,但我搜索並找不到一個好的答案呢。SQL存儲過程選擇多行並插入另一個表

我有一個看起來像這樣的存儲過程(開始):

Declare @idCC int 
Declare @TrStatus int 
Declare @FirstName varchar(50) 
Declare @LastName varchar(50) 
Declare @Email varchar(50) 
Declare @Plant varchar(50) 


SELECT @idCC=dbo.CC_Contacts.idCC, @FirstName=dbo.CC_Contacts.Firstname, @LastName=dbo.CC_Contacts.Lastname, @Email=dbo.CC_Contacts.Email, @Plant=dbo.CC_Plants.PlantName 
FROM   dbo.CC_Contacts INNER JOIN 
         dbo.CC_ContactGroups ON dbo.CC_Contacts.idCC = dbo.CC_ContactGroups.idCC INNER JOIN 
         dbo.CC_Plants ON dbo.CC_Contacts.idPlant = dbo.CC_Plants.idPlant CROSS JOIN 
         dbo.CC_Groups INNER JOIN 
         dbo.CC_ECPGroups ON dbo.CC_Groups.idGroup = dbo.CC_ECPGroups.idGroup INNER JOIN 
         dbo.ECP_ProbRpt ON dbo.CC_ECPGroups.ECPName = dbo.ECP_ProbRpt.ECPName 
WHERE (dbo.ECP_ProbRpt.ProbIdx = @PRid) AND (dbo.CC_Groups.IsPRGroup = 1) AND (dbo.CC_ECPGroups.Condition = 1) AND (dbo.CC_Contacts.Status = 1) AND 
         (dbo.CC_Contacts.PRnotify = 1) 

INSERT INTO [dbo].[ECP_TR_Recipients](idTr, TrStatus, idCC, FirstName, LastName, Email, Plant)      
VALUES (@idTr, '1', @idCC, @FirstName, @LastName, @Email, @Plant) 

的問題是選擇返回多個行和所有的人都需要被插入到另一個表。我真的不確定該從哪裏出發。任何想法或建議,將不勝感激。

我單獨測試了select查詢,效果很好。我只需要它遍歷結果並將它們全部插入即可。

感謝您的幫助!

+0

BTW:@idTR在存儲過程中的其他地方定義。 – PigsIncorporated

+0

而不是'INSERT INTO

)VALUES()',寫入'INSERT INTO
)SELECT FROM <您的其餘查詢>''。 [快速參考](http://www.w3schools.com/sql/sql_insert_into_select.asp) –

回答

2

你並不需要使用一個聲明只是使用insert into table1 column_name select column_name from table2,在你的例子是這樣

INSERT INTO [dbo].[ECP_TR_Recipients](idTr, TrStatus, idCC, FirstName, LastName, Email, Plant) 
SELECT dbo.CC_Contacts.idCC, dbo.CC_Contacts.Firstname, dbo.CC_Contacts.Lastname, dbo.CC_Contacts.Email, dbo.CC_Plants.PlantName 
FROM   dbo.CC_Contacts INNER JOIN 
         dbo.CC_ContactGroups ON dbo.CC_Contacts.idCC = dbo.CC_ContactGroups.idCC INNER JOIN 
         dbo.CC_Plants ON dbo.CC_Contacts.idPlant = dbo.CC_Plants.idPlant CROSS JOIN 
         dbo.CC_Groups INNER JOIN 
         dbo.CC_ECPGroups ON dbo.CC_Groups.idGroup = dbo.CC_ECPGroups.idGroup INNER JOIN 
         dbo.ECP_ProbRpt ON dbo.CC_ECPGroups.ECPName = dbo.ECP_ProbRpt.ECPName 
WHERE (dbo.ECP_ProbRpt.ProbIdx = @PRid) AND (dbo.CC_Groups.IsPRGroup = 1) AND (dbo.CC_ECPGroups.Condition = 1) AND (dbo.CC_Contacts.Status = 1) AND 
         (dbo.CC_Contacts.PRnotify = 1) 

如果你想在表中添加更多的靜態列,只要在SELECT語句中添加虛假列

INSERT INTO [dbo].[ECP_TR_Recipients](idTr, TrStatus, idCC, FirstName, LastName, Email, Plant) 
    SELECT @idTr as idTr, '1', dbo.CC_Contacts.idCC, dbo.CC_Contacts.Firstname, dbo.CC_Contacts.Lastname, dbo.CC_Contacts.Email, dbo.CC_Plants.PlantName 
+0

唯一的問題是插入上有兩列不是從select派生的。你如何添加插入值? – PigsIncorporated

+0

那兩列是靜態值嗎? –

+0

一個是靜態值,總是爲'1',另一個爲插入存儲過程的@idTr,但在命令持續時間內總是靜態的。 – PigsIncorporated