我希望在变量具有值的条件下执行WHERE子句的一部分。我曾尝试用许多不同的方式写这个,但总是遇到错误,并想知道是否有人可以提供帮助。
下面的代码是我当前的SQL语句,但如果我的@itemId为空,则不会返回任何内容。如果将@itemId作为值,我只想减少结果。
DECLARE @itemId nvarchar(max)
SET @itemId = 'someId'
SELECT
SalesOrdersItems.Id,
CASE
WHEN SalesOrderItems.ItemType = 'P' THEN Products.ProductId
WHEN SalesOrderItems.ItemType = 'S' THEN Sundries.SundryId
WHEN SalesOrderItems.ItemType = 'F' THEN FreightMethods.FreightMethodId
ELSE SalesOrderItems.FreeTextItem
END AS ItemId
FROM SalesOrderItems
LEFT OUTER JOIN Products ON SalesOrderItems.Product = Products.Product
LEFT OUTER JOIN Sundries ON SalesOrderItems.Sundry = Sundries.Sundry
LEFT OUTER JOIN FreightMethods ON SalesOrderItems.FreightMethod = FreightMethods.FreightMethod
WHERE
SalesOrdersItems.area LIKE 'SE%'
AND (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId)
我尝试过像这样编写最后一行(参见下面的代码),但它不起作用。
AND CASE
WHEN @itemId = '' THEN 1
ELSE (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId)
END
有没有人有任何想法我错了?
答案 0 :(得分:2)
如果我误会请告诉我,我假设如果你有一个空白的@itemID,你想要所有的结果,否则你会限制结果。
WHERE SalesOrdersItems.area LIKE 'SE%'
AND ((@itemId != ''
AND (Products.ProductId = @itemId
OR Sundries.SundryId = @itemId
OR FreightMethods.FreightMethodId = @itemId
OR SalesOrderItems.FreeTextItem = @itemId))
OR @itemId = '')
我相信我的parens是正确的,但他们可能是不平衡的。希望清楚地了解我的意图。
答案 1 :(得分:1)
...
WHERE
1 = CASE WHEN ... THEN 1 ELSE 0 END
...
答案 2 :(得分:0)
您可以使用NULLIF()
AND CASE
WHEN NULLIF(@itemId, '') IS NULL THEN 1
ELSE (Products.ProductId = @itemId OR Sundries.SundryId = @itemId OR FreightMethods.FreightMethodId = @itemId OR SalesOrderItems.FreeTextItem = @itemId)
END
答案 3 :(得分:0)
根据我的理解,你应该做类似下面的事情。
(Products.ProductId = @itemId OR ISNULL(@itemId, '') = '') OR
(Sundries.SundryId = @itemId OR ISNULL(@itemId, '') = '') OR
(FreightMethods.FreightMethodId = @itemId OR ISNULL(@itemId, '') = '') OR
(FreightMethods.FreeTextItem = @itemId OR ISNULL(@itemId, '') = '')
希望这会有所帮助!!