tags:

views:

86

answers:

3
SELECT * 
FROM dbo.tbh_table 
WHERE TopicID IN (
  SELECT value 
  FROM dbo.fn_split('19,',')
)

I have to change above query to execute result like below

SELECT * 
FROM dbo.tbh_table 
WHERE TopicID LIKE '%19,%'

My topicID values are like this 15,19,12,1 But split will give values are 15 19 12 1. because of which i am not able to execute the query.

any guidance will help

A: 

You could add your IDs to a table variable and then join with the table variable to determine if TopicID was in the table variable.

DECLARE @DesiredIDs TABLE (
   DesiredID INT
)

INSERT INTO @DesiredIDs (DesiredID) Values (15)
INSERT INTO @DesiredIDs (DesiredID) Values (19)
INSERT INTO @DesiredIDs (DesiredID) Values (12)
INSERT INTO @DesiredIDs (DesiredID) Values (1)

select * from tbh_table t 
left join @DesiredIDs d on d.DesiredID = t.TopicID 
where d.DesiredID is not null
Mayo
If I am reading the question right, his question isn't "how do I match 15 or 19 or 12 or 1" but "how do I match 19 to a topicId comma-delimited string, given that I have a table function to separate the string". So your solution doesn't work. Plus not needing a desiredIds table is precisely what the IN clause was invented for.
SquareCog
+2  A: 

Assuming that fn_split is a table valued function (TVF), returning a TABLE (value INT), use this:

SELECT  t.*
FROM    dbo.tbh_table t
CROSS APPLY
        dbo.fn_split(TopicID) split
WHERE   split.value = 19
Quassnoi
upvoted. I didn't know about cross apply. This is a sqlserver specific thing, right?
SquareCog
Right, and 15 chars
Quassnoi
A: 

If I understand your question correctly, you want something like this:

SELECT * 
FROM dbo.tbh_table 
WHERE 19 IN ( 
  SELECT value 
  FROM dbo.fn_split(TopicId,',')
)
SquareCog