2011-06-28 74 views
3

我想創建一個在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)) 

回答

6

這應該也行......

select 
    * 
from 
    Products 
where 
    Name like '%Hasbro%' and 
    (
     (@ProductID is null) or 
     (@ProductID is not null and ProductID = @ProductID) 
    ) 
+0

這工作完美!謝謝! – Halcyon

+1

這可以簡化爲:(@ProductId是NULL或ProductId = @ProductId) –

2

更簡單的方法是使用ISNULL

where 
    Name like '%Hasbro%' 
    and ProductID = ISNULL(@ProductID, ProductID) 

這樣一來,如果省略@ProductID(即,它在存儲過程調用NULL),那麼你就原值回落,並基本上它降到WHERE Name like '%Hasbro%' and ProductID = ProductID - 第二部分總是會是真的。

雖然根據您發佈的代碼,但它現在不是存儲過程。只要你知道,你不DECLARE參數一樣,在SQL Server中,您的存儲過程的聲明看起來像:

CREATE PROCEDURE [dbo].[YourStoredProcName] 
    @ProductID = NULL 
AS 
BEGIN 
    -- stuff goes here 
END 

然後,如果存儲過程被稱爲只是EXEC YourStoredProcName,然後@ProductIDNULL和那ISNULL()電話會工作。


編輯:除了這不是一個空列,在這種情況下,顯然這是工作。對於任何不可空列,這可能是最簡單的解決方案。

+0

當我運行這個結果相比,表中的行的總數量是非常小的。該表只有少數空產品ID。當我從產品運行select *時,productid不爲null,我得到1300多行。 – Halcyon

+0

你是否也在用類似'%Hasbro%'的名字過濾? –

相關問題