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!
@pi_colValue + 'AND Active = 1)doesn't have a space beforeAND, and you'll get a run-on statement like this:WHERE InternalOrgCode = 10110AND Active = 1