2016-07-28 59 views
0

我知道這是一個基本問題,但我似乎無法拿出正確的搜索詞組合來獲得我需要的答案。如果參數是-1,選擇所有記錄

我正在研究存儲過程,其中有一個名爲@AccountTypeId的參數。參數可以是1,2,3-1。如果@AccountTypeId-1它應該返回全部帳戶類型(1,23)。我可以寫一個SP很輕鬆地將過濾器的基礎上@AccountTypeId

CREATE PROCEDURE Accounts_SP (@AccountTypeId INT) 
AS 
SELECT * 
FROM Accounts 
WHERE AccountTypeId = @AccountTypeId 

問題是具有SP返回的所有AccountType■當@AccountTypeId-1

我這樣的WHERE子句中使用CASE聲明嘗試:

CREATE PROCEDURE Accounts_SP (@AccountTypeId INT) 
AS 
SELECT * 
FROM Accounts 
WHERE AccountTypeId IN (CASE @AccountTypeId WHEN -1 
          THEN (SELECT AccountTypeId FROM AccountTypes) 
          ELSE @AccountTypeId 
         END) 

但它給我下面的錯誤:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

我敢肯定有一個簡單的方法得到所有的記錄,我只是過分複雜的事情。有人可以請指點我正確的方向嗎?

回答

2

您可以使用OR語句,如果您發送-1並因此選擇所有行,該語句當然總是爲true。

SELECT * 
FROM Accounts 
WHERE AccountTypeId = @AccountTypeId 
OR @AccountTypeId = -1 
+0

我知道這是簡單的事情。在時間限制結束後我會接受答案。謝謝!! –

1

每次我面對這個要求(而且往往)的時候,我使用SQL Server中的COALESCE功能。 COALESCE返回第一個非空值,所以它會像這樣。請注意,@Param已更改爲支持NULL。

CREATE PROCEDURE Accounts_SP (@AccountTypeId INT = NULL) 
AS 
SELECT * 
FROM Accounts 
WHERE AccountTypeId = COALESCE(@AccountTypeId, AccountTypeId) 
相關問題