从select
语句中有条件地设置T-SQL变量的正确语法是什么?
我有如下代码:
select @CreationDate = dm.TS_UP
, @RegenerateDocument = dm.REGENERATEBLOB
, @CalculateRelativeToDate = case
when dm.REGENERATEBLOB is null then getdate()
when dm.REGENERATEBLOB = 'Y' then getdate()
when dm.REGENERATEBLOB = 'N' then coalesce(@ApprovalDate, getdate())
end
from doc_mgmt dm
where dm.ID_DOC = '11123'
and dm.ID_PRMRY_TYPE = @CID
and dm.ID_WRK_TYPE = @IID
请注意,该案例中的任何分支都没有以null
结尾。
但是我在使用@CalculateRelativeToDate
变量时遇到了麻烦,该变量有时以null
的形式出现。我不明白为什么会这样。实际上,在我正在测试的情况下,@RegenerateDocument
标志设置为Y
,所以我认为我应该得到getdate()
。但是我得到null
。
从select
语句中有条件地设置T-SQL变量的正确语法是什么?
答案 0 :(得分:2)
如果要确保设置值,可以使用聚合。没有let descriptionText = NSMutableAttributedString(string:"To learn more, check out our ", attributes: [:])
let linkText = NSMutableAttributedString(string: "Privacy Policy and Terms of Use", attributes: [NSAttributedString.Key.link: URL(string: example.com)!])
descriptionText.append(linkText)
的聚合查询总是返回恰好一行:
group by
如果您通常希望一行,那就没有问题。 select @CreationDate = max(dm.TS_UP),
@RegenerateDocument = max(dm.REGENERATEBLOB),
@CalculateRelativeToDate = (case when max(dm.REGENERATEBLOB) is null then getdate()
when max(dm.REGENERATEBLOB) = 'Y' then getdate()
when max(dm.REGENERATEBLOB) = 'N' then coalesce(@ApprovalDate, getdate())
end)
from doc_mgmt dm
where dm.ID_DOC = '11123' and
dm.ID_PRMRY_TYPE = @CID and
dm.ID_WRK_TYPE = @IID;
将返回该行的值。如果没有行匹配,则max()
的值将为max()
-似乎正是您所期望的。