日期:2014-05-18  浏览次数:20591 次

参数化查询时有办法传入NULL吗?
与此帖疑问近似
http://topic.csdn.net/t/20061013/09/5079299.html

如果把select count(*) from Table2 where ColumnA is NULL
换成参数化的select count(*) from Table2 where ColumnA is @para

那么@para怎么赋值才能传入NULL达到直接写IS NULL的效果呢?

——————————————————————————————————————
另外在insert的时候,比如
insert into Table2 (ColumnA,ColumnB) values (@para1,@para2)

使用参数@para1赋值为null,@para2赋值为DBNULL.Value,在数据库中均是存入了NULL。


——-----------------------------------
跟踪SQL SERVER的执行,TextData分别为

插入:
exec sp_executesql N'insert into Table2 (ColumnA,ColumnB) values (@para1,@para2)',N'@para1 nvarchar(50),@para2 nvarchar(50)',@para1=NULL,@para2=NULL

查询:
exec sp_executesql N'select count(*) from Table2 where ColumnA is @para',N'@para nvarchar(50)',@para=NULL

看不出明显不同,求解啊0.0

------解决方案--------------------
SQL code
--或者
create procedure pr_test
@para  varchar(32)=null
as
begin
    if len(@para)=0
    begin
    select count(*) from Table2 where ColumnA is NULL

    end
    else
    begin
    select count(*) from Table2 where ColumnA =@para

    end
end

------解决方案--------------------
单写SQL 肯定是不行。如果你的 @para存在有效的值
你的 
select count(*) from Table2 where ColumnA is NULL

select count(*) from Table2 where ColumnA is @para
都会错

存储过程 通用 包括了你所有值的特殊情况。
而且 存储过程第一次执行后 系统会保存其执行计划。以后就不用每次重新编辑生成执行计划了。就提高了效率
这就是存储过程 的好处之一


------解决方案--------------------
SQL code
select count(*) from Table2 
where (@para is not null and ColumnA =@para) or (@para is null and ColumnA is null)