1

I am trying to create a stored that will accept two values, a column name and a value. It will then check if there is a record that exists for the passed in column name with the passed in value. I've tried the following

CREATE PROCEDURE p_HasActiveReference
     @pi_colName varchar(100)
    ,@pi_colValue varchar(100)
AS
BEGIN
SET NOCOUNT ON      
    declare @sql varchar(1000)

    set @sql = 'IF EXISTS(SELECT TOP 1 p.PaymentId
                FROM Payments p
                WHERE ' + @pi_colName + ' = ' + @pi_colValue +     'AND Active = 1)

                    SELECT ''True'' AS RETVAL
                ELSE
                    SELECT ''False'' AS RETVAL'
    exec(@sql)  
 END

However, I always get this error

Conversion failed when converting the varchar value 'InternalOr' to data type int.

When I call the procedure with the following

p_HasActiveReference 'InternalOrgCode', '10110'

The internalOrgCode column is of value varchar(10)

I am not a SQL expert, so I am not even sure if what I need to achieve is even possible using that technique!

Thanks!

2
  • 2
    1. You're vulnerable to SQL injections with this. 2. Your code @pi_colValue + 'AND Active = 1) doesn't have a space before AND, and you'll get a run-on statement like this: WHERE InternalOrgCode = 10110AND Active = 1 Commented Aug 23, 2012 at 14:25
  • Thanks for the tip! I added a space before AND but still same error Commented Aug 23, 2012 at 14:34

1 Answer 1

3

At least one issue: you should be surrounding your string value with single quotes, and to escape those inside a string you need to double them up:

WHERE ' + @pi_colName + ' = ''' + @pi_colValue + ''' AND ...

You also may want to declare your @sql variable as something bigger than 100 characters! Looks like your string is getting truncated.

If the possible values for @pi_colName are finite, the data type is always string, and the columns are collation compatible, you could do something like this and avoid dynamic SQL:

SELECT ...
WHERE CASE @pi_colName 
  WHEN 'col1' THEN col1
  WHEN 'col2' THEN col2
END = @pi_ColValue;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it was the single quotes issue!
works perfectly with the CASE, it let me avoid dynamic strings concatenations and works well for both WHERE and ORDER BY, thanks !!

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.