使用插入并选择CTE

时间:2014-08-11 11:21:37

标签: sql sql-server-2012 common-table-expression return

我必须将记录插入到具有父子关系的两个表中。在PostgreSQL中,我编写了一个类似这样的代码:

WITH ins1 AS (
   INSERT INTO ccdb.bills
     (bill_id, source_system_id, mbc_bill_id, mbc_bill_no, cin, cust_connection_id, consumer_number, cust_type_flag)   

SELECT      nextval('ccdb.bills_seq') AS bill_id, 1, p.mbc_bill_id, p.mbc_bill_no,c.cin, p.cust_connection_id, COALESCE(p.consumer_num,p.applicant_num), p.cust_type_flag 
FROM   ccdb.o_bills_stg p
JOIN ccdb.consumers c USING (consumer_num)
JOIN ccdb.bill_type_master bt USING (bill_type_id)
JOIN ccdb.migrate_qtable mq ON p.ccdb_qtable_id = mq.id
WHERE  p.section_code = $1
AND mq.ddu_area = 2
AND mq.status_flag = 1
RETURNING mbc_bill_id,bill_id
)

INSERT INTO ccdb.bill_head_details
        (bill_id, charge_head_code, amount_billed,amount_paid, charge_head_descr, ccdb_update_time,creation_dt,created_by, tariff_id,demand_date)
SELECT i.bill_id,h.charge_head_code,h.amount_billed,h.amount_paid,null,now(),now(),'system',h.tariff_id,h.demand_date
FROM ins1 i
JOIN ccdb.o_bills_details_stg h ON h.mbc_bill_id = i.mbc_bill_id
JOIN ccdb.migrate_qtable mq ON h.ccdb_qtable_id = mq.id
WHERE mq.status_flag = 1
AND mq.ddu_area = 2
AND mq.section_code = $1;

此代码是函数的一部分。我想在SQL Server 2012中实现相同的功能,我该怎么做呢?

0 个答案:

没有答案