Dynamic conditions in WHERE clause

2019-06-24 06:42发布

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?

4条回答
手持菜刀,她持情操
2楼-- · 2019-06-24 07:07

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)
查看更多
Anthone
3楼-- · 2019-06-24 07:10

I'm not certain I understand you, but if my understanding is correct, you can do the following (NOTICE: injection vulnerable)

DECLARE @SQL varchar(500) = 'SELECT * FROM tbl_users ' + @username

EXEC @SQL
查看更多
闹够了就滚
4楼-- · 2019-06-24 07:21

You are really not supposed to be concatenating SQL keywords and parameters into one single string as shown in some of the responses above for reasons of opening the doors to SQL injection (One of the contributors actually called it out. That's a wise Warning!).

Instead, you are supposed to parameterize your SQL and execute the system SP sp_executesql.

A very good code example is shown in this StackOverflow posting.

查看更多
Viruses.
5楼-- · 2019-06-24 07:27

From what I know, this is not going to work. You're going to need to generate the script you want to execute and use the exec command.

查看更多
登录 后发表回答