日期:2014-05-19  浏览次数:20443 次

疯狂求救!!对一个 sql语句的疑问.为空与有值在sql server里面必须用if吗??
小弟写了个过程,代码如下
select   name,age  
  from   User_table
where     @in_name   is   null   or   name   =   @in_name;
我想实现@in_name为空就查全部,不为空则查指定的条件
分两种情况,如果输入参数@in_name为空执行@in_name   is   null(换成@in_name   =   null也一样)   ,不为空就执行name   =   @in_name,在oracle这样写是正确的,但是在sql   server中有问题.未必用if来判断吗,如果像这种条件多了,不是有很多if语句.各位大哥在开发中是怎样做的,有没简便的方法,谢谢

------解决方案--------------------
select [name],age
from User_table
where @in_name is null or [name] = @in_name;
------解决方案--------------------
貌似你的写法是对的

------解决方案--------------------
--测试
declare @User_table table (
name varchar(20),
age int
)

insert @User_table select
'a ',1
union all select
'b ',1

declare @in_name varchar(20)

select name,age
from @User_table
where @in_name is null or name = @in_name

set @in_name= 'a '

select name,age
from @User_table
where @in_name is null or name = @in_name

--结果
name age
-------------------- -----------
a 1
b 1

(所影响的行数为 2 行)

name age
-------------------- -----------
a 1

(所影响的行数为 1 行)

------解决方案--------------------
应该是你的参数操作的问题,存储过程应该这么写

create proc pr_test
@in_name varchar(20)=null
as

select name,age
from User_table
where @in_name is null or name = @in_name

go

--调用
exec pr_test 'a '
go

exec pr_test
go