SQL Server:存储过程将表内容添加到另一个表

时间:2014-08-20 09:40:23

标签: sql sql-server

如何使用存储过程将参数查询的结果添加到另一个表?

这是我的选择查询文字:

SELECT        
    dbo.PortfolioH.Epic, 
    dbo.PortfolioH.AlertRatings,
    dbo.UserAccounts.Email, 
    dbo.PortfolioH.UserN
FROM            
    dbo.PortfolioH 
LEFT OUTER JOIN
    dbo.UserAccounts ON dbo.PortfolioH.UserN = dbo.UserAccounts.UserN
GROUP BY 
    dbo.PortfolioH.Epic, 
    dbo.PortfolioH.AlertRatings, 
    dbo.UserAccounts.Email,
    dbo.PortfolioH.UserN
HAVING        
    (dbo.PortfolioH.AlertRatings = N'yes')

我想附加到AlertEmails

所在的表dbo.PortfolioH.Epic = @Epic

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:3)

只需使用标准INSERT.....SELECT构造,该构造将从查询中插入数据,如下所示:

INSERT INTO dbo.AlertsEmails (Epic, AlertRatings, Email, UserN, AlertType)

SELECT        dbo.PortfolioH.Epic, dbo.PortfolioH.AlertRatings,
dbo.UserAccounts.Email, dbo.PortfolioH.UserN, 1 As AlertType

FROM            dbo.PortfolioH LEFT OUTER JOIN
dbo.UserAccounts ON dbo.PortfolioH.UserN = dbo.UserAccounts.UserN

GROUP BY dbo.PortfolioH.Epic, dbo.PortfolioH.AlertRatings, dbo.UserAccounts.Email,
dbo.PortfolioH.UserN
HAVING        (dbo.PortfolioH.AlertRatings = N'yes') ;

它只运行查询,但不是返回结果集,而是将结果行插入表中。请注意,我在INSERT部分添加了AlertType列,并在SELECT部分添加了固定值,因为它们必须完全匹配。