简体   繁体   中英

How to INSERT into 1 table and UPDATE another table in one query

I have a question on how to write a single query to insert and update. Below is the scenario. I am trying to use 1 query for the part that is enclosed in (-----)

CREATE TABLE #TEMP
(
    Ref VARCHAR(10),
    Num INT,
    [Status] VARCHAR(3)
)

INSERT INTO #TEMP
VALUES ('A123', 1, 'A3'), ('A123', 2, 'A3'), ('A123', 3, 'A3'),
       ('B123', 1, 'A1'), ('B123', 2, 'A3'), 
       ('C123', 1, 'A1'), ('C123', 2, 'A2'), ('C123', 3, 'A3');

SELECT
    Ref, 
    CASE WHEN A.TotalCount = A.DenialCount THEN 1 ELSE 0 END IsDenial
    --CASE WHEN A.TotalCount <> A.DenialCount Then 1 else 0 end IsApproval
INTO 
    #TEMP1
FROM
    (SELECT
         Ref, COUNT(Num) TotalCount,
         SUM(CASE WHEN [Status] = 'A1' THEN 1 ELSE 0 END) ApprovedCount,
         SUM(CASE WHEN [Status] = 'A2' THEN 1 ELSE 0 END) PartialApprovalCount,
         SUM(CASE WHEN [Status] = 'A3' THEN 1 ELSE 0 END) DenialCount
     FROM
         #temp
     GROUP BY
         Ref) A

UPDATE A
SET A.[Status] = CASE WHEN IsDenial = 1 THEN 'A3' ELSE 'A1' END 
FROM #TEMP A
JOIN #TEMP1 B ON A.Ref = B.Ref

SELECT * FROM #TEMP
SELECT * FROM #TEMP1

DROP TABLE #TEMP
DROP TABLE #TEMP1

Any help would be appreciated.

"INSERT into 1 table and UPDATE another table in one query"

Nope. Some DBMSes support the idea of 'upsert' but that's insert/update in a single table.

Your looking for the MERGE statment. However I see several issues with the SQL in your post. In short it is generally more efficient to use set theory instead of thinking of optimisations per statement.

Rather than update, why not join in the data thats inserted into temp into the second query and produce the result you require?

hint ' SELECT 'ABC' as a, '123' as b, 456 as c UNION '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM