当前位置: 代码迷 >> Sql Server >> 参数化查询时有办法传入NULL吗?解决办法
  详细解决方案

参数化查询时有办法传入NULL吗?解决办法

热度:96   发布时间:2016-04-27 12:34:24.0
参数化查询时有办法传入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

[email protected] NULL的效果呢?

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

[email protected],@para2赋值为DBNULL.Value,在数据库中均是存入了NULL。


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

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

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

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

------解决方案--------------------
SQL code
--或者create procedure pr_test@para  varchar(32)=nullasbegin    if len(@para)=0    begin    select count(*) from Table2 where ColumnA is NULL    end    else    begin    select count(*) from Table2 where ColumnA [email protected]    endend
------解决方案--------------------
单写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 [email protected]) or (@para is null and ColumnA is null)
  相关解决方案