当前位置: 代码迷 >> Sql Server >> sql存储过程动态添加条件[写法]解决方案
  详细解决方案

sql存储过程动态添加条件[写法]解决方案

热度:424   发布时间:2016-04-27 14:52:02.0
sql存储过程动态添加条件[写法]
CREATE PROCEDURE [dbo].[Find_]
@daeStart smalldatetime , @daeEnd smalldatetime , @strBmph varchar(20) , @strField varchar(5) , @strText varchar(20)
as

declare @i int , @strSql varchar(100)
set @i = 1

if @strBmph <> '' set @strSql = ' and bmph = ' + @strBmph
if @strField <> '' and @strText <> '' set @strSql = @strSql + ' and ' + @strField + ' = ' + @strText

begin

/*以下语法错误,请大家赐教。*/
select * from aaa where bDel = 0 + @strSql 

end
go
exec [Find_] '2011-6-10','2011-6-30' , '人事部' , '' ,''
go
drop procedure find_

------解决方案--------------------
SQL code
CREATE PROCEDURE [dbo].[Find_]@daeStart smalldatetime , @daeEnd smalldatetime , @strBmph varchar(20) , @strField varchar(5) , @strText varchar(20)asdeclare @i int , @strSql varchar(100)set @i = 1if @strBmph <> '' set @strSql = ' and bmph = ' + @strBmphif @strField <> '' and @strText <> '' set @strSql = @strSql + ' and ' + @strField + ' = ' + @strTextbegin/*以下语法错误,请大家赐教。*/exec('select * from aaa where bDel = 0 '+ @strSql  )endgoexec [Find_] '2011-6-10','2011-6-30' , '人事部' , '' ,''godrop procedure find_
------解决方案--------------------
CREATE PROCEDURE [dbo].[Find_]
@daeStart smalldatetime , 
@daeEnd smalldatetime , 
@strBmph varchar(20) , 
@strField varchar(5) , 
@strText varchar(20)
as

declare @i int , @strSql varchar(100)
set @i = 1
set @strSql='select * from aaa where bDel = 0 '
if @strBmph <> '' set @strSql = ' and bmph = ' + @strBmph
if @strField <> '' and @strText <> '' set @strSql = @strSql + ' and ' + @strField + ' = ' + @strText
print (@strSql)
exec (@strSql) 


------解决方案--------------------
探讨
十分感谢,要加exce('这样来执行')

因为语句较长,如果不用 exce('...')有其它代替方法吗?

------解决方案--------------------
把你的语句放入临时表 然后insert into #tb exec...
------解决方案--------------------
用一个字符串起来 exec ...
------解决方案--------------------
感觉像多条件的查询的语句,楼主完全可以不用这样判断,假如20多个条件
你会更蒙

个人建议,像这样写更好点:
select * from test where (字段1=条件 or 1=1) and (字段2<>条件 or 1=1) and (字段3 like 条件 or 1=1)
  相关解决方案