我想創建一個在proc的WHERE部分中具有可選參數的存儲過程。我的C#代碼可以傳入null或此proc的有效產品ID。這裏是:如何在SQL Server中包含一個可選的空參數
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
if @ProductID is not null
begin
and ProductID = @ProductID
end
此代碼不起作用。如果產品ID爲空,我希望它僅查找名稱爲「孩之寶」的產品。如果產品ID不爲空,我希望它查找名稱爲「孩之寶」的產品並匹配產品ID。
謝謝!
更新:
以下是工作代碼。謝謝大家幫助我得到這個!
declare @ProductID int
set @ProductID = null
select
*
from
Products
where
Name like '%Hasbro%'
and ((@ProductID is null) or (@ProductID is not null and ProductID = @ProductID))
這工作完美!謝謝! – Halcyon
這可以簡化爲:(@ProductId是NULL或ProductId = @ProductId) –