SQL 服务器/TSQL 使用 isnull 转换 smalldatetime
SQL Server / TSQL cast smalldatetime using isnull
我正在尝试对 table 中的列进行简单检查:
If (endDate is null)
use smalldatetime '12/31/2200'
else
use endDate from column
这是我的存储过程:
ALTER PROCEDURE [dbo].[getCostByDate] @date smalldatetime, @productID int
AS
SELECT cost
FROM testDB.dbo.product_cost
WHERE @date between startDate and isNull(endDate,cast('12/31/2200' as smalldatetime)) and product_id = @productID
我试图 'cast' 将“12/31/2200”格式化为小日期时间,但出现错误:
"The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value."
这是关键:
and isNull(endDate,cast('2029-04-25T15:50:59.997' as smalldatetime))
你必须给出整个日期,即使它是一个小日期时间...另外,你不能使用 2200,我想它太遥远了...
问题是 smalldatetime 的日期范围是 1900-01-01 到 2079-06-06,而您的值超过了上限。解决方案是使用范围内的值,或其他日期类型,如 datetime 或 datetime2。
例如,cast('12/31/2078' as smalldatetime)
会起作用。
我正在尝试对 table 中的列进行简单检查:
If (endDate is null)
use smalldatetime '12/31/2200'
else
use endDate from column
这是我的存储过程:
ALTER PROCEDURE [dbo].[getCostByDate] @date smalldatetime, @productID int
AS
SELECT cost
FROM testDB.dbo.product_cost
WHERE @date between startDate and isNull(endDate,cast('12/31/2200' as smalldatetime)) and product_id = @productID
我试图 'cast' 将“12/31/2200”格式化为小日期时间,但出现错误:
"The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value."
这是关键:
and isNull(endDate,cast('2029-04-25T15:50:59.997' as smalldatetime))
你必须给出整个日期,即使它是一个小日期时间...另外,你不能使用 2200,我想它太遥远了...
问题是 smalldatetime 的日期范围是 1900-01-01 到 2079-06-06,而您的值超过了上限。解决方案是使用范围内的值,或其他日期类型,如 datetime 或 datetime2。
例如,cast('12/31/2078' as smalldatetime)
会起作用。