SQL Server:如果存在;别的
我有一个表 A:
ID value
1 100
2 101
2 444
3 501
还有表 B
ID Code
1
2
现在,如果表 A 中存在 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
我确信 BEGIN;END 或 IF EXIST;ELSE 中存在一些问题。 基本上,如果 IF 部分中的 select 语句存在,我想绕过 else 部分,反之亦然。例如,如果 IF=part 的 select 语句是:
(select MAX(value) from #A where id = 4)
它应该只填充 123,因为 ID = 4 不存在!
I have a tableA:
ID value
1 100
2 101
2 444
3 501
Also TableB
ID Code
1
2
Now I want to populate col = code of table B if there exists ID = 2 in tableA. for multiple values , get max value.
else populate it with '123'. Now here is what I used:
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
I am sure there is some problem in BEGIN;END or in IF EXIST;ELSE.
Basically I want to by-pass the else part if select statement in IF-part exist and vice- versa. For example if select statement of IF=part is:
(select MAX(value) from #A where id = 4)
It should just populate 123, coz ID = 4 do not exist !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑
我想添加您的
IF
语句似乎不起作用的原因。当您对聚合执行EXISTS
时,它始终为true
。即使ID
不存在,它也会返回一个值。当然,它是NULL
,但它返回了它。相反,请执行以下操作:您将到达
IF
语句的ELSE
部分。现在,这是一个更好的、基于集合的解决方案:
它的优点是能够在整个表而不是单个 id 上运行。
EDIT
I want to add the reason that your
IF
statement seems to not work. When you do anEXISTS
on an aggregate, it's always going to betrue
. It returns a value even if theID
doesn't exist. Sure, it'sNULL
, but its returning it. Instead, do this:and you'll get to the
ELSE
portion of yourIF
statement.Now, here's a better, set-based solution:
This has the benefit of being able to run on the entire table rather than individual ids.
试试这个:
Try this:
我知道距离原来的帖子已经有一段时间了,但我喜欢使用 CTE,这对我有用:
I know its been a while since the original post but I like using CTE's and this worked for me: