WHERE子句中的动态条件 [英] Dynamic conditions in WHERE clause
本文介绍了WHERE子句中的动态条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
其中
条件。 让我说我有这个查询:
SELECT *
FROM tbl_Users
现在,我有一个名为 @username
,我想用来建立一个动态的
其中
条件(通过我的程序可能是1或更多的条件)。要实现类似的东西,我使用以下语句:
SELECT *
FROM tbl_Users
@username - - 此参数可能包含条件字符串,例如其中usr_Username = 5和usr_first_name like%Frank%等
可以这样做吗?
解决方案
你将不得不打破动态的sql
它会运行如下:
declare @ sql varchar(max)
set @sql ='
SELECT *
FROM tbl_Users
WHERE'+ @username
exec(@ sql)
I have a stored procedure and would like to know if its possible to build up a dynamic where
condition based on a parameter.
Lets say I have this query:
SELECT *
FROM tbl_Users
Now, I have a parameter called @username
, which I would like to use to build up a dynamic where
condition (which through my program might be 1 or more conditions). To achieve something like that I use the following statement:
SELECT *
FROM tbl_Users
@username -- where this parameter might hold a condition string such as "Where usr_Username = 5 and usr_first_name like '%Frank%' etc
Is it possible to do something like this?
解决方案
You're going to have to break into dynamic sql for this.
it would run something like this:
declare @sql varchar(max)
set @sql = '
SELECT *
FROM tbl_Users
WHERE ' + @username
exec (@sql)
这篇关于WHERE子句中的动态条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文