我遇到了一些问题,当我向日期时间变量传递一个空值时,它存储为默认日期(1900-01-01 00:00:00.000)
我写了一个条件语句
ruby \
-e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" \
</dev/null
我希望两个都应返回“是”。不幸的是,第一个条件返回“否”,第二个条件返回“是”。谁能解释该功能的工作原理。
答案 0 :(得分:2)
''
没有datetime
的值。如您所见,''
将隐式转换为值19000101
。如果您有未知的日期,请使用NULL
(毕竟NULL
的意思是“未知”)。这会将您的声明更改为:
DECLARE @l_date datetime, --I don't set the value as it'll already be NULL
@l_date1 datetime = GETDATE();
IF @l_date IS NOT NULL
SELECT 'Yes' AS [@l_date],
@l_date AS D;
ELSE
SELECT 'No' AS [@l_date],
@l_date AS D;
IF @l_date1 IS NOT NULL
SELECT 'Yes' AS [@l_date1],
@l_date1 AS D;
ELSE
SELECT 'No' AS [@l_date1],
@l_date1 AS D;
(请注意,这仍然分别返回'No'
和'Yes'
。)
答案 1 :(得分:2)
指定空字符串时,documented default value用于时间类型。考虑:
DECLARE
@datetime datetime = ''
,@smalldatetime smalldatetime = ''
,@datetime2 datetime2 = ''
,@date date = ''
,@time time = ''
,@datetimeoffset datetimeoffset = ''
SELECT
@datetime AS datetime
,@smalldatetime AS smalldatetime
,@datetime2 AS datetime2
,@date AS date
,@time AS time
,@datetimeoffset AS datetimeoffset;
结果:
+-------------------------+---------------------+-----------------------------+------------+------------------+------------------------------------+
| datetime | smalldatetime | datetime2 | date | time | datetimeoffset |
+-------------------------+---------------------+-----------------------------+------------+------------------+------------------------------------+
| 1900-01-01 00:00:00.000 | 1900-01-01 00:00:00 | 1900-01-01 00:00:00.0000000 | 1900-01-01 | 00:00:00.0000000 | 1900-01-01 00:00:00.0000000 +00:00 |
+-------------------------+---------------------+-----------------------------+------------+------------------+------------------------------------+
尽管有时使用零代替空字符串来表示默认值,但是对于较新的datetime2
,date
,time
和datetimeoffset
类型,不允许使用此值
答案 2 :(得分:0)
您可以尝试
declare @l_date datetime=0 ,@l_date1 datetime = getdate()
if @l_date IS NOT NULL
select 'Yes' as '@l_date',@l_date D
else
select 'No' as '@l_date',@l_date D
if @l_date1 IS NOT NULL
select 'Yes' as '@l_date1',@l_date1 D
else
select 'No' as '@l_date1',@l_date1 D