新手,求教个关于动态条件拼接的问题。
修改别人的存储过程,其中有一个存储过程,在程序里拼接好的查询条件作为参数传给存储过程,存储过程中判断这个条件是否为空,如果不为空,加上这个条件,如果为空,什么也不做。
类似这样:
传进来个参。。@Query NVARCHAR(MAX)=null
这个参可能是name like '%zhang%' 或者 age=23 and sex=0 等等这种格式的,程序拼过来的。
然后存储过程中原来是用字符串拼接的sql语句,最后判断参数然后拼接的。
比如:
@sql=N'select * from table1 where id=xx ' + isnull('and ' + @Query,'')'
where col=case when @变量 is null or @变量='' then 1 else @变量 end and id=xx
string strWhere = "";
string sql = "select * from table1 where 1=1";
if(string.isnullorempty(name ))
{
sql += "and name like'%" + strWhere + "%'";
}
1
where col=case when @变量 is null or @变量='' then col else @变量 end and id=xx