SQL Server:IF EXISTS; 其他

Bhu*_*ngh 57 sql sql-server if-statement exists

我有一张桌子A:

ID value
 1  100
 2  101
 2  444
 3  501
Run Code Online (Sandbox Code Playgroud)

表B

ID Code
1
2
Run Code Online (Sandbox Code Playgroud)

现在,如果tableA中存在ID = 2,我想填充表B的col =代码.对于多个值,获取最大值.否则用'123'填充它.现在这是我使用的:

if exists (select MAX(value) from #A where id = 2)
 BEGIN
 update #B
 set code = (select MAX(value) from #A where id = 2)
 from #A
 END

 ELSE 

 update #B
 set code = 123
 from #B
Run Code Online (Sandbox Code Playgroud)

我确信在BEGIN; END或IF EXIST; ELSE中存在一些问题.基本上,如果IF部分中的select语句存在,我想绕过else部分,反之亦然.例如,如果IF = part的select语句是:

(select MAX(value) from #A where id = 4)
Run Code Online (Sandbox Code Playgroud)

它应该只填充123,因为ID = 4不存在!请教育!提前致谢

Der*_*omm 89

编辑

我想补充你的IF陈述似乎不起作用的原因.当你EXISTS在聚合上进行时,它总会如此true.即使ID不存在,它也会返回一个值.当然,它是NULL,但它返回它.相反,这样做:

if exists(select 1 from table where id = 4)
Run Code Online (Sandbox Code Playgroud)

你会得到ELSE你的IF陈述部分.


现在,这是一个更好的,基于集合的解决方案:

update b
  set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
  on b.id = a.id
where
  b.id = yourid
Run Code Online (Sandbox Code Playgroud)

这样做的好处是能够在整个表上运行而不是单个ID.


Cha*_*ana 6

试试这个:

Update TableB Set
  Code = Coalesce(
    (Select Max(Value)
    From TableA 
    Where Id = b.Id), 123)
From TableB b
Run Code Online (Sandbox Code Playgroud)