2014-11-14 133 views
-1
create procedure sp1 
(
    @p1 int = null 
) 
as 
begin 
    select f1, f2, f3 
    from table1; 
end 

如何僅在@ p1不爲空時將「where」子句添加到select查詢(其中f1 = @ p1)?如果@ p1爲null,則返回所有行!基於輸入參數值的SQL Server存儲過程

回答

1
create procedure dbo.sp1 
(
    @p1 int = null 
) 
as 
begin 
select f1, f2, f3 
from dbo.table1 where(@p1 is not null and [email protected]) 
end 

OR

可以使用

這裏查詢返回的所有行如果@p1爲空(因爲@ P1返回trueNULL

create procedure dbo.sp1 
(
    @p1 int = null 
) 
as 
begin 
select f1, f2, f3 
from dbo.table1 where(@p1 is null OR [email protected]) 
end 
+0

但是我想在@ p1爲空時選擇所有行! – Jalil 2014-11-14 17:56:29

+0

@Jalil你可以使用第二個 – 2014-11-14 17:59:00

+1

@Jalil那麼你應該明確地在你的問題中提出這個要求 – Lamak 2014-11-14 18:01:52

1

試試這個。該where clause將工作只有當@p1 is not null

SELECT f1, 
     f2, 
     f3 
FROM dbo.table1 
WHERE @p1 IS NOT NULL 
     AND f1 = @p1 

如果你想返回所有的值,如果@ P1爲null,則只是一個ISNULL功能。如果@ p1爲Not Null,則將返回[email protected]值,否則將返回所有值。試試這個

SELECT f1, 
     f2, 
     f3 
FROM dbo.table1 
WHERE f1 = isnull(@p1,f1) 
+0

也許不是代碼運行,但它使得它更容易理解你的意圖是什麼。 – user2366842 2014-11-14 17:59:03

1

在case @ p1爲空,下面將返回每一件事情,如果有我是一種價值,它會適用於這種情況。

WHERE @p1 is NULL OR [email protected]