2016-03-05 47 views
3

我正在創建一個sql server存儲過程,它將輸入作爲逗號分隔productid或選項「全部」。當用戶傳入逗號分隔的productid時,查詢應輸出所有產品ID的數據。我用「IN」語句做了這個。當用戶輸入選項「ALL」時,查詢應顯示所有產品的銷售數據。 有沒有其他簡單的方法,我可以讓我的查詢下面的工作「ALL」以及逗號分隔「ProductId的」?我的查詢是下面:查詢工作的個人參數以及「所有」的情況下

-- Inputs 
Declare @Product varchar(max) = '0022,0033'; 

-- Code to split string and insert individual productIds into a temp table. 
DECLARE @XML AS XML 
DECLARE @Delimiter AS CHAR(1) =',' 
CREATE TABLE #ProductParams (ProductId INT) 
SET @XML = CAST(('<X>'+REPLACE(@Product,@Delimiter ,'</X><X>')+'</X>') AS XML) 
INSERT INTO #@ProductParams 
SELECT N.value('.', 'INT') AS ID FROM @XML.nodes('X') AS T(N) 

-- Sales query for all the products selected. How can I change the below query so that it displays sales for all products when parameter "All" is passed ? 
select * from SalesTable where ProductId in (select ProductId from #ProductParams) 

我不想做到以下幾點:

If(option is ALL) 
run this query 
If(option is comma seperated product ids) 
run another query. 
+0

您可以在一個字符串,用逗號隔開傳遞的參數一定堅持下去。然而,我想建議傳遞一個表到存儲過程,而不是所有的參數:http://stackoverflow.com/questions/28464523/how-to-pass-an-array-of-numbers-to- a-stored-procedure/28475248#28475248我相信由此產生的查詢將更容易與兩個表的連接。 – Ralph

回答

3

考慮到當用戶選擇ALL選項@ProductNULL

DECLARE @Product VARCHAR(max) = '0022,0033'; -- When user chose ALL then this will be NULL 

SELECT * 
FROM salestable 
WHERE productid IN (SELECT productid 
        FROM #productparams) 
     OR @Product IS NULL 

正如在評論中提到你可以看看table types這應該避免解析CSV到程序內的單個行Ë

create type product_list as table 
(
productid INT -- Chose relevant datatype 
); 

阿爾特程序

​​

要調用

declare @prod_list product_list 

Insert into @prod_list(productid) values (0022),(0033) 

Exec proc_name @prod_list