将参数添加到where子句sql

时间:2017-02-27 10:36:37

标签: sql-server-2012

我是SQL的初学者,我正在尝试运行以下SP。

DECLARE @stringStatus varchar(100)

--Check for status value
IF @Status is NULL
BEGIN
    set @stringStatus = ''
END
ELSE 
BEGIN
    set @stringStatus = ' and ps.Status = ' + CAST(@Status as varchar)
END

select * from Projects p
    join projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) + @stringStatus

上述目的是获取所有行@Status is NULL,并过滤行,如果参数已分配给@Status @Category(varchar)和@Status(int)是IN paramateres

当@Status为NULL时,这可以正常工作,即我得到所有记录。但是如果我传递一个参数,比如@Status = 2,即使有一些记录可用,执行也不会返回任何行。

首先,我如何得到我想要的结果?其次,如果没有if条件块,有没有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

实际上,你的结果是

select * from something where ps.Category ='some string, containing and ps.Status= inside' 

因此预期结果为空行集 你想要这样的东西(希望状态是数字,而不是字符串)

select * from Projects p
    join projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) and
     (@Status is NULL OR ps.Status = @Status)

好的,这里是不信任的测试: - )

declare @projects table 
(
    pid int,
    name nvarchar(20),
    category int
);

declare @projectstatus table
(
    pid int,
    Category int,
    status int
);

insert into @projects values
(1,'Project 1', 1),(2,'Project 2',1),(3,'Project 3',1),(4,'Project 4',1),(5,'Project 5',1);

insert into @projectstatus values
(1,1,1),(2,1,2),(3,1,3),(4,1,2),(5,1,NULL);


declare @Category int =null;
declare @Status int;

--first of all, do not understand, what is the logic with category
--category in one table should be the same, than in other table or specified?
--ok, you said with category everything is ok, do not test category, test status 

--test with null
set @Status=null


select * from @Projects p
    join @projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) and
     (@Status is NULL OR ps.Status = @Status)

--test with existing status     
set @Status=1
select * from @Projects p
    join @projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) and
     (@Status is NULL OR ps.Status = @Status)

--test with not existing status     
set @Status=10
select * from @Projects p
    join @projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) and
     (@Status is NULL OR ps.Status = @Status)

答案 1 :(得分:0)

您可以通过以下方式简单地设置条件以获得所需的结果

--Check for status value
IF @Status is NULL
  BEGIN
    select * from Projects p
    join projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) 
  END
ELSE 
  BEGIN
    select * from Projects p
    join projectstatus ps on p.pid = ps.pid
    where ps.Category = isnull(@Category, p.Category) + @stringStatus
  END

由于