SQL 比较正在更新的字段
我有以下查询:
UPDATE #Temp_SessionItem SET [Status] =
CASE
WHEN ([AddressFK] IS NULL OR [StatusFK] IS NULL) AND [Status] = 1
THEN 3
WHEN [AddressFK] IS NOT NULL AND [StatusFK] IS NOT NULL AND [Status] = 1
THEN 2
END
问题是,当它执行时,它实际上并没有给出我期望的结果。即,如果 [AddressFK
] 或 [StatusFK
] 为 NULL,它不会将 [
。相反,它只是在应该添加 3 时尝试将 Status
] 字段的值设置为 3NULL
添加到 Status。
如果我删除表达式的 AND [Status] = 1
部分,它会返回 3,但随后它还会更新 [Status] = 1
以外的值。
我在这里缺少什么明显的东西吗?
我正在使用 SQL Server 2008。
编辑:
在 Royi Namir 向我指出之后,我意识到问题一定出在执行该查询的存储过程中。具体来说,#Temp_SessionItem 只是一个临时表。在上面提到的查询之后,我尝试使用以下查询更新原始表:
-- update the status of the original session item table
UPDATE UploadSessionItem SET [Status] = T.[Status]
FROM #Temp_SessionItem AS T
WHERE UploadSessionItem.UploadSessionItemId = T.ID
..这显然不起作用,因为所有 [Status
] 项目仍然有 1
I have the following query:
UPDATE #Temp_SessionItem SET [Status] =
CASE
WHEN ([AddressFK] IS NULL OR [StatusFK] IS NULL) AND [Status] = 1
THEN 3
WHEN [AddressFK] IS NOT NULL AND [StatusFK] IS NOT NULL AND [Status] = 1
THEN 2
END
The problem is that when it's executed it doesn't actually give me the result I am expecting. i.e. it doesn't set the value of [Status
] field to 3 in case [AddressFK
] or [StatusFK
] is NULL
. Instead, it just tries to add NULL
to Status when it should add 3.
If I remove the AND [Status] = 1
part of the expression it does return 3 but then it updates also the values that are not [Status] = 1
.
Is there anything obvious that I'm missing here?
I'm using SQL Server 2008.
EDIT:
After Royi Namir pointed out to me I realized that the problem must be further down the stored procedure that this query is being executed in. Specifically, #Temp_SessionItem is just a temporary table. After the upper mentioned query I'm trying to update the original table with the following query:
-- update the status of the original session item table
UPDATE UploadSessionItem SET [Status] = T.[Status]
FROM #Temp_SessionItem AS T
WHERE UploadSessionItem.UploadSessionItemId = T.ID
..which is obviously not working since all the [Status
] items there are still 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想影响当前
STATUS
为1
的行,则需要一个WHERE
子句:您显示的更新工作正常:
结果:
因此,如果问题在其他地方,则它不在您向我们展示的代码示例中。
If you only want to affect rows with a current
STATUS
of1
, you need aWHERE
clause:The update you've shown works fine:
Result:
So if the problem is elsewhere, it's not in a code sample you've shown us yet.
@bojanskr , [AddressFK] 和 [AddressFK] 两者之一[StatusFK] 不为 null ,或者您的 staus!=1
更新前 status 的值为多少?他是什么样的类型?
在此粘贴此查询的结果:
@bojanskr , either both [AddressFK] & [StatusFK] are not null , or your staus!=1
what is the value of status before updating ? what kind of type he is ?
paste the result from this query here :
您没有默认情况,因此当这两个条件都不成立时,您会得到 NULL。你可以这样重写:
You don't have a default case, so you get NULL when neither of those conditions are true. You could rewrite it like this: