August 19, 2015 at 8:28 am
I must be overlooking something...
I am trying to do something like
declare @txtSearchMajors nvarchar(500) = 'U101,U304,P748,I333,O948'
select *
from tblMajors
where txtMajorID IN (@txtSearchMajors)
I can't seem to get this to work. There must be something simple I am missing to this.
August 19, 2015 at 8:39 am
You're comparing against a single value that have commas in it, not separate values.
To achieve what you want, you need a splitter. It can be found in here: http://www.sqlservercentral.com/articles/Tally+Table/72993/
And you could use it like this:
declare @txtSearchMajors nvarchar(500) = 'U101,U304,P748,I333,O948'
select *
from tblMajors
where txtMajorID IN (SELECT Item FROM dbo.DelimitedSplitN4K(@txtSearchMajors, ','))
--OR
select *
from tblMajors m
JOIN dbo.DelimitedSplitN4K(@txtSearchMajors, ',') s ON m.txtMajorID = s.Item
August 19, 2015 at 9:17 am
Probably the best way here, taking the appropriate precautions against SQL Injection, would be a lick of dynamic SQL.
--Jeff Moden
Change is inevitable... Change for the better is not.
August 19, 2015 at 11:24 am
My DBAs frown on dynamic SQL... so I think I will go with the splitter function. Which there was way to say treat this as a CSV rather than a value with commas easier.
August 19, 2015 at 11:52 pm
Kevlarmpowered (8/19/2015)
My DBAs frown on dynamic SQL...
They REALLY need to get over that. Properly written dynamic SQL is SQL Injection proof, safe, fast, and will cache an execution plan just like any other SQL.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply