1

I am using SQL input parameters in a stored procedure to select different rows with various WHERE clauses. This is being done using dropdown lists in a view. The issue is that I am allowing the user to select the operator in the where clause using a dropdownlist.

CREATE PROCEDURE SingleClauseReport
    @selectedRows varchar(1000),
    @testLeftInput varchar(100),
    @testOperatorInput varchar(10),
    @testRightInput varchar(100)
AS
BEGIN
    Select @selectedRows
    from Test
    where @testLeftInput + ' ' + @testOperatorInput + ' ' + @testRightInput;
END
GO

I am getting an error stating that a condition is expected. Is it possible to do this? Otherwise I would just have to use one operator, like:

where @testLeftInput = @testRightInput;

2 Answers 2

3

What you're trying won't work. You have two options: dynamic sql, or a re-writing the procedure to have one query for each possible operator and then decide which to execute based on the parameter. I strongly recommend the latter.

CREATE PROCEDURE SingleClauseReport
    @selectedRows varchar(1000),
    @testLeftInput varchar(100),
    @testOperatorInput varchar(10),
    @testRightInput varchar(100)
AS
BEGIN
  If @testOperatorInput  = '=' 
  Begin
    Select @selectedRows
    from Test
    where @testLeftInput = @testRightInput;
  End
  Else If @testOperatorInput  = '>' 
  Begin
    Select @selectedRows
    from Test
    where @testLeftInput > @testRightInput;
  End
  --...
END
Sign up to request clarification or add additional context in comments.

2 Comments

Be careful of performance problems using this approach. Without a couple of additional things this can suffer greatly from cached execution plans. sqlinthewild.co.za/index.php/2009/09/15/…
Okay, I'm trying to figure out the least costly way to use this strategy with an AND in the WHERE clause (So there would be two operators), but that may be enough for another question
0

Don't do this:

AS
BEGIN

declare @sql nvarchar(max)

set @sql = N'Select ' + @selectedRows 
+ ' from Test where ' + @testLeftInput + ' ' 
+ @testOperatorInput + ' ' 
+  @testRightInput;

execute sp_executesql @sql

END

1 Comment

I would highly advise you NOT to use this method. It is wide open to sql injection. This is pretty much a textbook example of how sql injection works.

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.