将CTE中的数据插入表中

时间:2017-09-19 05:35:06

标签: sql sql-server

我有以下语句,我想将结果插入到具有相同列的表中:

with Salary as    
(   
    select 
        a.id, a.name, a.Netsalary, a.final_sal 
    from
       (select * from worker) a
    left join 
       (select * from Discount) b on a.id = b.id
)    
select 
    *, Netsalary / final_sal SalPer  
from 
    Salary 

2 个答案:

答案 0 :(得分:1)

BEGIN TRAN

--You need to put the CTE first and then combine the INSERT INTO
--with your select statement.
--Also, the "AS" keyword following the CTE's name is not optional:

with Salary as
(
select a.id,a.name,a.Netsalary ,a.final_sal
from
(select * from worker) a
left join
(select * from Discount ) b on a.id = b.id
)
INSERT INTO Table_Name (
id,
name,
Netsalary,
final_sal
)  
SELECT * FROM Salary
ROLLBACK TRAN

答案 1 :(得分:0)

也许有充分的理由使用CTE,也许不是。我不愿意。 试试这个

    insert into tablename
    select 
        a.id, 
        a.name, 
        a.Netsalary, 
        a.final_sal , 
        a.Netsalary / a.final_sal as SalPer 
    from
        worker a
        left join Discount b on a.id = b.id
    where 1=1
        and filterconditions
        and filterconditions
        and filterconditions