我知道这个问题可能听起来像是重复的,但是我搜索过但找不到一个好的答案。
我有一个存储过程(已启动),如下所示:
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 :(得分: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