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