0

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

我当前的 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'
4

1 回答 1

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'

@巴兹1nga:

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)
于 2012-06-21T11:20:07.583 回答