简体   繁体   English

SQL默认的ELSE值

[英]SQL The Default ELSE Value

in the following sql query i have a select case without else 在下面的SQL查询中,我有一个选择情况,没有其他

 SET dateformat mdy 
    DECLARE @DATE1 DATETIME 
    SET @DATE1 = '12/31/2011' 
    DECLARE @DATE2 DATETIME 
    SET @DATE2 = '06/01/2012' 


    UPDATE tablx
    SET xdate = case WHEN xdate is null and odate BETWEEN @Date1 AND @Date2 then odate end

does the existance of else make difference, in the above case would the xdate value be filled with NULL if the condition is not met even if i didnt write ELSE NULL ? else的存在是否有所不同,在上述情况下,即使我没有写ELSE NULL如果条件不满足,xdate值是否也会用NULL填充?

It doesn't make any semantic difference ELSE NULL is the default if omitted. 它不会产生任何语义差异。如果省略,则默认为ELSE NULL

Perhaps including the redundant ELSE explicitly might be clearer for potential readers unaware of this fact though. 但是,对于潜在的不知道这一事实的读者来说,也许明确地包括冗余ELSE可能会更清楚。

From the MSDN documentation on CASE : CASE的MSDN文档中:

ELSE else_result_expression ELSE else_result_expression

Is the expression returned if no comparison operation evaluates to TRUE. 如果没有比较运算的结果为TRUE,则返回表达式。 If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. 如果忽略此参数,并且没有比较运算的结果为TRUE,则CASE返回NULL。


On a side note, it's a better habit to get into to write your date literals as: 附带说明一下,将日期文字写成以下内容是一个更好的习惯:

DECLARE @DATE1 DATETIME 
SET @DATE1 = '20111231'

Because such literals (YYYYMMDD, no separators) aren't ambiguous - you can then ignore the DATEFORMAT settings that are in effect. 由于此类文字(YYYYMMDD,无分隔符)并不明确-您可以忽略生效的DATEFORMAT设置。

Yes they would. 是的,他们会的。

For example, if you have the values 例如,如果您有值

create table tablx (xdate datetime, odate datetime)

insert into tablx values ('2012-01-01', '2012-01-02')
insert into tablx values (null,         '2012-01-02')
insert into tablx values (null,         '2013-11-12')
insert into tablx values ('2013-11-11', '2013-11-12')

The first, third, and fourth rows would be updated to null, and the second would be updated to '2012-01-02', so in effect 第一,第三和第四行将更新为null,第二行将更新为'2012-01-02',因此实际上

case WHEN <something> then odate end

is equivalent to 相当于

case WHEN <something> then odate else null end

But i would prefer the second version, as it is more explicit and obvious. 但是我更喜欢第二个版本,因为它更加明确和明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM