34,838
社区成员




/*
对比两个表中的记录数量是否一致,不用while,如何做?匹对上的就update表里的is_ok字段为'y'
*/
IF OBJECT_ID('tempdb.dbo.#out') IS NOT NULL
DROP TABLE #out
CREATE TABLE #out(code VARCHAR(10),price NUMERIC(18,2),amount INT,is_ok VARCHAR(1) DEFAULT 'n')
INSERT INTO #out(code, price, amount)
SELECT 'A',10,20 UNION ALL
SELECT 'A',10,20 UNION ALL
SELECT 'A',11,20 UNION ALL
SELECT 'A',11,30 UNION ALL
SELECT 'A',12,40 UNION ALL
SELECT 'A',12,20
IF OBJECT_ID('tempdb.dbo.#in') IS NOT NULL
DROP TABLE #in
CREATE TABLE #in(code VARCHAR(10),price NUMERIC(18,2),amount INT,is_ok VARCHAR(1) DEFAULT 'n')
INSERT INTO #in(code, price, amount)
SELECT 'A',10,10 UNION ALL
SELECT 'A',10,10 UNION ALL
SELECT 'A',10,20 UNION ALL
SELECT 'A',11,10 UNION ALL
SELECT 'A',11,10 UNION ALL
SELECT 'A',11,15 UNION ALL
SELECT 'A',12,40 UNION ALL
SELECT 'A',12,20
IF OBJECT_ID('tempdb.dbo.#out') IS NOT NULL
DROP TABLE #out
CREATE TABLE #out(code VARCHAR(10),price NUMERIC(18,2),amount INT,is_ok VARCHAR(1) DEFAULT 'n')
INSERT INTO #out(code, price, amount)
SELECT 'A',10,20 UNION ALL
SELECT 'A',10,20 UNION ALL
SELECT 'A',11,20 UNION ALL
SELECT 'A',11,30 UNION ALL
SELECT 'A',12,40 UNION ALL
SELECT 'A',12,20
IF OBJECT_ID('tempdb.dbo.#in') IS NOT NULL
DROP TABLE #in
CREATE TABLE #in(code VARCHAR(10),price NUMERIC(18,2),amount INT,is_ok VARCHAR(1) DEFAULT 'n')
INSERT INTO #in(code, price, amount)
SELECT 'A',10,10 UNION ALL
SELECT 'A',10,10 UNION ALL
SELECT 'A',10,20 UNION ALL
SELECT 'A',11,10 UNION ALL
SELECT 'A',11,10 UNION ALL
SELECT 'A',11,15 UNION ALL
SELECT 'A',12,40 UNION ALL
SELECT 'A',12,20
;with t as (
select a.code as a_code,a.price as a_price,a.amount as a_amount,b.code as b_code,b.price as b_price,b.amount as b_amout
,(case when a.code=b.code and a.price=b.price and a.nid=b.nid and a.amount=b.amount then 1 else 0 end) as upd
from (
select *,ROW_NUMBER() over(partition by code,price,amount order by amount) as nid from #in
) a
full join (
select *,ROW_NUMBER() over(partition by code,price,amount order by amount) as nid from #out
) b on a.code = b.code and a.price=b.price and a.nid=b.nid and a.amount=b.amount
)
update #in
set is_ok='y'
from t
where a_code=#in.code and a_price=#in.price and a_amount=#in.amount and upd=1
select * from #in
select * from #out
update a set a.is_ok ='y' from #out a
inner join #in b on a.code = b.code
where a.price = b.price and a.amount = b.amount
这样子?--1. 更新 #out
UPDATE A
SET A.is_ok='y'
FROM #out AS A INNER JOIN #in AS B
ON A.code=B.code
WHERE A.price=B.price AND A.amount=B.amount
--2. 更新 #in
UPDATE B
SET B.is_ok='y'
FROM #out AS A INNER JOIN #in AS B
ON A.code=B.code
where A.price=B.price AND A.amount=B.amount
update 需要修改的表 set 字段=修改的数据 from
需要修改的表 inner join 源数据 on。。。。。。。。
where 条件。。。。。。。