我遇到了从存储过程中获取数据的问题。该过程用于插入和更新记录,这将确定调用时设置的参数。我的例子是假设DATE类型参数的默认值为NULL,即它们尚未传递给sp。我已将代码分解为一小部分来修复,而不是包含整个过程代码,如下所示:
-- these would be sp parameters
declare @CustomerId int = 15
declare @Indicator varchar(5) = 'Yes'
declare @ProjectTypeId tinyint = 1
declare @FutureEffectiveDate as date = null
SELECT
CASE @FutureEffectiveDate
WHEN NULL THEN
CASE @Indicator
WHEN 'Yes' THEN
-- can only be 1, 2 or 3 to return relevant date
CASE @ProjectTypeId
WHEN 1 THEN DI.[NextFormalEffectiveDate]
WHEN 2 THEN DI.[NextInterimEffectiveDate]
WHEN 3 THEN DI.[NextAccountingEffectiveDate]
END
-- data should be NULL if @Indicator not 'Yes'
ELSE NULL
END
ELSE @FutureEffectiveDate
END AS [FutureEffectiveDate]
FROM
[_Staging].[DataImport_2] AS DI
JOIN
[CustomerView] AS CV ON CV.[CustomerNumber] = DI.[BillingInvoiced]
JOIN
[ProjectType] AS PT ON PT.[ProjectType] = DI.[ProjectType]
WHERE
CV.[CustomerID] = @CustomerId AND
PT.[ProjectTypeID] = @ProjectTypeId
因此,我们的想法是,对于字段包含文本“是”的记录,并根据该记录的项目类型,它会选择三个日期之一。如果该字段不是“是”,那么它应该返回NULL,忽略项目类型。如果date参数为NOT null,则它应该只返回传入的参数。结果将作为列'FutureEffectiveDate'返回。根据我的示例数据,我希望返回日期,因为相关字段为“是”,而NextFormalEffectiveDate列具有值(项目类型为1)。
奇怪的是,如果排除外部CASE语句,它就可以工作。所以问题在于根据DATE参数确定要做什么,但我不明白为什么外部CASE语句会破坏结果。
答案 0 :(得分:4)
在CASE语句中检查@FutureEffectiveDate
NULL
的方式是错误的。这是一个小型演示
declare @FutureEffectiveDate as date = null
Select Case @FutureEffectiveDate when NULL then 1 else 0 end
以上查询将生成0
。因为上面的CASE
语句验证了输入表达式,如@FutureEffectiveDate = NULL
,它将失败。应使用NULL
运算符
IS
进行比较
以下是比较NULL
SELECT CASE
WHEN @FutureEffectiveDate IS NULL THEN
CASE ..