views:

138

answers:

3

I have a requirement.

Given say Test1,Test2, I have to perform a like operation.

Something like

select * from tblname where column_name like('Test1%','Test2%');

i.e. these strings are comma separated

How do I solve this?

This is in SQL SERVER 2005.

Thanks in Advance

+3  A: 

You will need to create a TSQL statement like this:

SELECT
    *
FROM
    tblname
WHERE
    column_name like 'Test1%'
    OR
    column_name like 'Test2%'

You need an OR for each case

HollyStyles
+2  A: 
 declare @v varchar(50)
 declare @sql varchar(1000)
 declare @c int

 set @v = ltrim(rtrim(' An Gu an')) -- this is your search creteria
 set @sql = 'select * from tblname where '
 set @c = charindex(' ', @v)

 while @c > 0
  begin
     set @sql = @sql + 'column_name ' + ' like ''%' + 
                       left(@v,@c-1) +'%'' OR ';
   set @v = right(@v, len(@v)-@c)  
   set @c = charindex(' ', @v)
  end
 set @sql = @sql + ' column_name like ''%'+@v +'%'''

      --sql now contains
      --select * from tblname where 
      -- column_name  like '%An%' OR 
      -- column_name  like '%Gu%' OR  
      -- column_name like '%an%'

 exec( @sql)
TheVillageIdiot
+1  A: 

Sql server 2005, try this

--Lookup Table
DECLARE @Values TABLE(
     Column_Name VARCHAR(MAX)
)

INSERT INTO @Values (Column_Name) SELECT 'A'
INSERT INTO @Values (Column_Name) SELECT 'B'
INSERT INTO @Values (Column_Name) SELECT 'ATADA'
INSERT INTO @Values (Column_Name) SELECT 'TADAA'
INSERT INTO @Values (Column_Name) SELECT 'Test123A'
INSERT INTO @Values (Column_Name) SELECT '1Test123A'

--Lookup string and delim
DECLARE @LookupString VARCHAR(MAX)
DECLARE @Delim VARCHAR(1)

SET @LookupString = 'Test1,Test2,TADA'
SET @Delim = ',';

--CREATE A LOOKUP TABLE FOR SPLIT STRINGS
WITH substrings (Val, Remainder) AS(
    SELECT CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN @LookupString ELSE LEFT(@LookupString,CHARINDEX(@Delim,@LookupString)-1) END,
      CASE WHEN CHARINDEX(@Delim,@LookupString) = 0 THEN '' ELSE RIGHT(@LookupString,LEN(@LookupString) - CHARINDEX(@Delim,@LookupString)) END
    UNION ALL 
    SELECT CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN Remainder ELSE LEFT(Remainder,CHARINDEX(@Delim,Remainder)-1) END,
      CASE WHEN CHARINDEX(@Delim,Remainder) = 0 THEN '' ELSE RIGHT(Remainder,LEN(Remainder) - CHARINDEX(@Delim,Remainder)) END
    FROM substrings
    WHERE CHARINDEX(@Delim,Remainder) >= 0 AND Val != '' AND Remainder != ''
)
SELECT  v.Column_Name,
     substrings.Val
FROM    @Values v INNER JOIN
     substrings ON v.Column_Name LIKE substrings.Val + '%'
astander