4

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?

2
  • Not in T-SQL itself; you can build that SELECT statement in your front-end language (C#, VB.NET or whatever) and send it to SQL Server once it's complete, or you can use dynamic SQL inside a T-SQL statement to build up your query as a string and then "execute" that string - but you cannot just "parametrize" part of yuor T-SQL query like this....
    – marc_s
    Aug 4, 2011 at 17:01
  • 1
    You can do it with string-building (like several folks below have demonstrated), but just a word of caution -- avoid dynamic sql if you have any choice in the matter -- it's very much a pain-in-the-neck to write, maintain, upgrade, troubleshoot, etc.
    – Chains
    Aug 4, 2011 at 17:08

4 Answers 4

5

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)
2

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
1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.