0

On my asp.net project, there are instances where a server side filter function in C# is building an SQL WHERE clause, then passing it into an SQL stored procedure for example,

Filter produces a string variable with a value like “WHERE Qty < 5 AND Price > 10”.

The relevant part of the Stored Procedure is like:

Exec (‘
    Select Name, Location
    From Users
    + ‘@passedInWhereClause’
‘)

As you can see, we have to do an EXEC command on a string built with the passed in variable containing the where clause that was generated by C# code on the server side. I would really like a way to eliminate the EXEC and make the SQL code look more professional, instead of a giant string wrapped with an EXEC. Is there any better way to do this?

3
  • 7
    Here be SQL injection dragons... Commented May 1, 2012 at 21:57
  • This is another question like yours. The short answer is NO. Commented May 1, 2012 at 21:59
  • 1
    Have you considered using EF or Linq-To-SQL to do this instead? Commented May 1, 2012 at 22:04

2 Answers 2

1

You should consider optional parameters, example

WHERE (@Type = NULL OR @Type = '' OR @Type = Type)

This allows you to pass a NULL or blank to the SP to ignore the where clause, or you pass a value to have the where clause applied.

Sign up to request clarification or add additional context in comments.

1 Comment

We actually do optional parameters elsewhere in our code. This should work here as well. Thanks!
0

No, there is not a better way to do this, as you are building Dynamic SQL to execute.

If you want to do it better, then don't run Dynamic SQL.

The Curse and Blessings of Dynamic SQL

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.