I have a situation where in I need to create a dynamic IN clause in the query.
Right now the query looks like this:
DECLARE @transactIds varchar(50);
DECLARE @transactionTypeID int = 10;
IF (@transactionTypeID != 0 AND @transactionTypeID = 10)
BEGIN
SET @transactIds = '12'+', '+'20'+', '+'21'+', '+'23'
END
ELSE
SET @transactIds = CAST(@transactionTypeID as varchar(3))
SELECT TOP 10 *
FROM Transactions
WHERE transactionTypeID IN (@transactIds)
Running this query, I get this error:
Conversion failed when converting the varchar value '12, 20, 21, 23' to data type int.
I know a better approach would be to put these values in temp table and then use select from that temp table inside the IN
clause and that is what I am using right now.
But using the table approach takes around 20 secs to run the SP.
When I use values directly in the in clause it runs in 2 secs.
Now, the code shown above is just a part of huge SP that I cannot change, so I need to look for a fix around this only.
Thanks in advance for any help.