插入由存储过程提取的表数据

时间:2017-01-18 12:18:12

标签: sql-server join stored-procedures select-insert

我有一个存储过程,它借助于连接从不同的表中获取数据。

以下是它的外观

ALTER PROCEDURE profinalinstexpensesonid
    (@from varchar(50),
     @to varchar(50),
     @trainer varchar(50),
     @sonvinid varchar(50)
    )          
AS              
BEGIN              
    SELECT
        instructoreexpense.sonvinid,
        CONVERT(VARCHAR, sonvininsert.date, 105) AS date,
        sonvininsert.brandname,              
        SUBSTRING(sonvininsert.zone, 1, 1) AS zone,              
        sonvininsert.location,              
        sonvininsert.area,              
        companysonvinunitvenue.venuename,            
        sonvininsert.venue,              
        sonvininsert.instructore,              
        sonvininsert.trainingno,              
        instructoreexpense.amount,              
        finalinstructoreexpense.amount AS amount1,              
        finalinstructoreexpense.utno,              
        finalinstructoreexpense.paymentid,              
        CONVERT(VARCHAR, finalinstructoreexpense.issuedate, 105) AS issuedate
    FROM
        instructoreexpense               
    LEFT OUTER JOIN   
        sonvininsert ON sonvininsert.sonvinid = instructoreexpense.sonvinid
                     AND sonvininsert.status = '0'                
    LEFT OUTER JOIN
        finalinstructoreexpense ON finalinstructoreexpense.sonvinid = instructoreexpense.sonvinid                
    LEFT OUTER JOIN
        companysonvinunitvenue ON companysonvinunitvenue.id = sonvininsert.comsonvinid                         
    WHERE
        sonvininsert.date BETWEEN CONVERT(DATETIME, @from, 105)  
                              AND CONVERT(datetime, @to, 105)     
        AND sonvininsert.trainer = (SELET empname 
                                    FROM trainerdetails 
                                    WHERE trid = @trainer)
        AND instructoreexpense.sonvinid NOT IN (SELECT CAST(Item AS INTEGER)
                                                FROM SplitString(@sonvinid, ','))
    ORDER BY
        instructoreexpense.sonvinid
END 

正如您所看到的,此过程是从不同的表中检索多个列,现在在此存储过程的末尾,我想将所有正在提取的数据插入到表2 invoice中。

我需要在这做什么?

我只想将此存储过程提取的数据插入到另一个表中,我想在此存储过程本身中执行此操作。

我希望能让你明白

2 个答案:

答案 0 :(得分:0)

您只需在选择前添加insert into

INSERT INTO invoice (<Columns list>)
SELECT ....

答案 1 :(得分:0)

INSERT INTO invoice (<<column list>>)
EXEC profinalinstexpensesonid @from=..., @to=...

请记住,为发票表指定的列列表的顺序应与查询的输出相同。

点击此链接https://msdn.microsoft.com/en-us/library/ms174335.aspx