+ -
当前位置:首页 → 问答吧 → sql存储过程动态添加条件[写法]

sql存储过程动态添加条件[写法]

时间:2011-12-20

来源:互联网

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_

作者: mzcih   发布时间: 2011-12-20

SQL code
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

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

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

作者: qianjin036a   发布时间: 2011-12-20

十分感谢,要加exce('这样来执行')

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

作者: mzcih   发布时间: 2011-12-20

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) 

作者: zhaowenzhong   发布时间: 2011-12-20

引用 2 楼 mzcih 的回复:
十分感谢,要加exce('这样来执行')

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

把你的语句放到一个varchar的变量里
然后执行
例如
declare @sql varchar(1000)
set @sql='select * from tb'
exec(@sql)

作者: pengxuan   发布时间: 2011-12-20

感谢以上的关注,因为语句较长,可能会有句头,句中,句尾加入条件位置不一定。

作者: mzcih   发布时间: 2011-12-20

把你的语句放入临时表 然后insert into #tb exec...

作者: fredrickhu   发布时间: 2011-12-20