日期:2014-05-17  浏览次数:20501 次

关于如何执行字符串中的命令语句
本帖最后由 cyh027 于 2013-11-22 12:09:22 编辑
小弟写了个条件分支过滤查询条件的存储过程,但遇到了一个问题。我有两个参数,参数1,参数2,如果参数1不为空的时候,参与过滤,反之不参与过滤,参数2不为空的时候,参与过滤,反之不参与过滤。

use table1
declare @sql_com nchar(40)
declare @sql_where nchar(40)
if (@参数1 <> '')
begin
set @sql_where =  @sql_where + ' and 条件1=参数1 '
end
if (@参数2 <> '')
begin
set @sql_where = @sql_where + ' and  条件2=参数2 '
end
set sql_where= ltrim(sql_where)--去除左边所有空格,便于计算
set @sql_where = ' where ' +SUBSTRING(@sql_where,4,len(@sql_where)-3)--去除第一个and,得到正确的过滤字符串

set @sql_com = 'select * from tbale1' +  @sql_where --得到想要的命令字符串

--现在问题出现在这里了,我想执行@sql_com里存储的字符串,请问各位大神,后面要怎么写啊?

------解决方案--------------------
记得结贴
------解决方案--------------------



use table1
declare @sql_com nchar(40)
declare @sql_where nchar(40)
if (@参数1 <> '')
begin
set @sql_where =  @sql_where + ' and 条件1=参数1 '
end
if (@参数2 <> '')
begin
set @sql_where = @sql_where + ' and  条件2=参数2 '
end
set sql_where= ltrim(sql_where)--去除左边所有空格,便于计算
set @sql_where = ' where ' +SUBSTRING(@sql_where,4,len(@sql_where)-3)--去除第一个and,得到正确的过滤字符串

set @sql_com = 'select * from tbale1' +  @sql_where --得到想要的命令字符串

--现在问题出现在这里了,我想执行@sql_com里存储的字符串,请问各位大神,后面要怎么写啊?

--打印语句
select @sql_com

--执行语句
exec(@sql_com)