是否可以在SQL中使用不同的变量类型重新创建此逻辑?

时间:2015-02-03 20:39:20

标签: sql sql-server

目前我在SQL Server的SQL脚本中有这个WHERE子句。

where (isNull(@InsuranceKey,isnull(InsuranceKey,0)) = isnull(InsuranceKey,0))

目前@InsuranceKey传递了一个INTInsuranceKey也是数据库中的INT

但是,这种情况正在发生变化,以便@InsuranceKey成为@InsuranceKeysVARCHAR(MAX)和逗号分隔的保险密钥列表。

如何以另一种方式重新创建此逻辑?我一直在努力。

到目前为止,我相信:

((@InsuranceKeys <> '' AND InsuranceKey in (Select ID From GetIntegerList(@InsuranceKeys))) OR (@InsuranceKeys = ''))

是准确的逻辑等价物:

WHERE isNull(@InsuranceKey, InsuranceKey) = InsuranceKey

但我正在努力比这更进一步。

1 个答案:

答案 0 :(得分:1)

除非我误认为你的陈述的逻辑等同物

where (isNull(@InsuranceKey,isnull(InsuranceKey,0)) = isnull(InsuranceKey,0))

where InsuranceKey is null or InsuranceKey = InsuranceKey or InsuranceKey = @InsuranceKey

因为这些是你正在处理的场景。

您可以将其重写为

where InsuranceKey is null or InsuranceKey = coalesce(@InsuranceKey,InsuranceKey)

所以,如果你现在有一个逗号分隔的InsuranceKey值列表,你将它们传递给一个返回InsuranceKey值列表的函数,那么这样的东西可能会起作用

where InsuranceKey is null or InsuranceKey in (Select ID 
                                                From GetIntegerList(@InsuranceKeys)
                                                Union
                                                select InsuranceKey)