我试图执行以下操作:
Declare @Customers nvarchar(MAX) = '15000, 15011'
--Declare @Customers nvarchar(MAX) = NULL
--IF A THEN B ELSE C
--((Not A) or B) AND (A or C)
SELECT SD.CustomerNumber, SD.CustomerName,
CASE WHEN F.CustomerNumber IS NOT NULL THEN 1 ELSE 0 END HasDiscount
From [dbo].[SubscriberDetails] As SD
LEFT JOIN [dbo].[FamilyCustomer] F
On F.CustomerNumber = SD.CustomerNumber
WHERE
((NOT @Customers IS NULL) OR F.CustomerNumber IS NOT NULL) AND (@Customers IS NULL OR SD.CustomerNumber IN (SELECT * FROM dbo.iter$ListToTable(@Customers)))
我试图做的是传递一串逗号分隔值" 15000,15011,16000 ......" OR NULL进入@Customers param。我使用了来自here的函数,它接受了一个字符串 然后在我的存储过程中,我想检查:
If Customers is Null then:
F.CustomerNumber IS NOT NULL
Else (@Customsers is not null Therefor)
SELECT * FROM dbo.iter$ListToTable(@Customers)
一切正常如果@Customers至少传递了一个值,但我得到"Cannot insert the value NULL into column 'number', table '@tbl'; column does not allow nulls. INSERT fails." when passing in null
我做错了什么? 感谢
答案 0 :(得分:3)
问题是SQL中的[\w.]*
没有短路,因此OR
会传递给null
。我认为最干净的解决方案是将函数更改为接受iter$ListToTable
输入。
另一个选择是在这个sproc中使用一个表值:
null
并将您的选择更改为:
DECLARE @temp_Customers TABLE (@cust int)
IF (@Customers IS NOT NULL)
BEGIN
INSERT INTO @temp_Custoers
SELECT * FROM dbo.iter$ListToTable(@Customers)
END