查询以处理单个参数以及“全部”情况

时间:2016-03-05 02:38:43

标签: sql sql-server sql-server-2012

我正在创建一个sql server存储过程,它将输入作为逗号分隔的productid或选项“All”。当用户传入逗号分隔的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.

1 个答案:

答案 0 :(得分:3)

考虑到用户何时选择ALL选项,@Product将为NULL

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 
);

更改程序

Alter procedure proc_name(@prod_list product_list)
as
BEGIN
SELECT * 
FROM   salestable 
WHERE  productid IN (SELECT productid 
                     FROM   @prod_list) 
        OR (select count(1) from @Product) = 0
END

致电

declare @prod_list product_list

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

Exec proc_name @prod_list
相关问题