加入2个表,比较列并更新第3列

时间:2012-06-21 11:15:21

标签: sql sql-server database

我正在编写一个sql语句(见下文),它比较了2个不同的表table1和table2上的2个序列号。如果序列号存在,那么我希望table1上的另一列更新为'yes',如果table1中的序列号不存在于table2中,我想更新为'no'

我当前的sql语句工作正常,必要时用“是”填充列。我的问题是,当序列号不存在时,不是放置“否”,而是更新为NULL。我的where语句很重要,因为我只想比较两个表中日期和安装匹配的两个表上的序列号。我不想比较每一行。感谢

UPDATE dbo.table1
    SET [Match] = CASE WHEN dbo.table2.[Serial Number] IS NOT NULL
    THEN 'yes' ELSE 'no' END
        FROM dbo.table1 LEFT OUTER JOIN dbo.table2
            ON dbo.table2.[Serial Number] = dbo.table1.[Serial Number]
        Where dbo.table1.[Date] = 'JAN11' AND 
              dbo.table1.[Install] = 'new' AND
              dbo.table2.[Date] = 'JAN11' AND 
              dbo.table2.[Install] = 'new'

1 个答案:

答案 0 :(得分:2)

将WHERE条件置于JOIN的条件:

UPDATE dbo.table1
SET [Match] = CASE WHEN dbo.table2.[Serial Number] IS NOT NULL
THEN 'yes' ELSE 'no' END
    FROM dbo.table1 LEFT OUTER JOIN dbo.table2
        ON dbo.table2.[Serial Number] = dbo.table1.[Serial Number]
    AND dbo.table1.[Date] = 'JAN11' AND 
          dbo.table1.[Install] = 'new' AND
          dbo.table2.[Date] = 'JAN11' AND 
          dbo.table2.[Install] = 'new'

@ Baz1nga:

WHERE导致过滤掉行,因此值的设置不会被分配回table1。

试试这个:

create table tblA
(
x int, y varchar(10)
);


create table tblB
(
x int, some_date varchar(10), serial_number int
);


insert into tblA(x,y) values(1,'www');
insert into tblB(x,some_date,serial_number) values(1,'yyy',76);

print 'First update';
update tblA
set y = case when tblB.serial_number is not null then 'Yes' else 'No' end
from tblA 
left join tblB on tblB.x = tblA.x 
where tblB.some_date = 'JAN11';

select * from tblA;

print 'Second update';
update tblA
set y = case when tblB.serial_number is not null then 'Yes' else 'No' end
from tblA 
left join tblB on tblB.x = tblA.x 
and tblB.some_date = 'JAN11';

select * from tblA;

输出:

(1 row(s) affected)

(1 row(s) affected)
First update

(0 row(s) affected)
x           y
----------- ----------
1           www

(1 row(s) affected)

Second update

(1 row(s) affected)
x           y
----------- ----------
1           No

(1 row(s) affected)
相关问题