December 23, 2012 at 6:37 am
Hello all,
I am trying to select row from a table where the column contains values from a list. I tried the following but that query gave me an error (Conversion failed when converting the varchar value '1 OR [AttributeID] = 3 OR [AttributeID] = 6 OR [AttributeID] = 2808' to data type int.):
DECLARE @strSearch VARCHAR(100) = '1,3,6,2808'
SELECT *
FROM [AttributeList]
WHERE [AttributeID] = REPLACE(@strSearch, ',', ' OR [AttributeID] = ')
The [AttributeID] is an integer type column and i use SQL Server 2012.
Can someone help me with this, and is this the most efficient way to search?
Best christmas wishes
Mike
December 23, 2012 at 7:33 am
Dynamic SQL (watch for SQL injection) or a string splitter function. I recommend the latter. Search this site for 'Delimited8kSplit'
Oh, and as for why your attempt failed, that equates to this:
SELECT *
FROM [AttributeList]
WHERE [AttributeID] = '1 OR [AttributeID] = 3 OR [AttributeID] = 6 OR [AttributeID] = 2808';
ie where the attribute is equal to that long string, which I'm sure you'll agree isn't going to do what you want
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
December 23, 2012 at 5:31 pm
GilaMonster (12/23/2012)
Dynamic SQL (watch for SQL injection) or a string splitter function. I recommend the latter. Search this site for 'Delimited8kSplit'
Here's the link for the DelimitedSplit8K splitter.
http://www.sqlservercentral.com/articles/Tally+Table/72993/
If you need something more sophisticated or need to handle something longer than 8K bytes, I strongly recommend a CLR.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply