Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Table as follows(Tablename Batch)
Bthid   Facid
 1      1,4,6
 2      5,9,11
 3      4
 4      11

Datatype as follows
Bthid  bigint
Facid  varchar(40)

Query as follows
SQL
select Bthid from bthfac where Facid = '4'
When i run the above query output as follows
Bthid
     3

But i want the output as follows
Bthid
    1
    3
Because Facid 4 is also there in the Bthid 1 in the above table Batch
Posted
Updated 25-Sep-13 18:57pm
v2

when using like if you will search record like below,
where facid like '%1%' it will show wrong o/p (will show record for 11 also because it contains 1)

either you should saparate tables or parse facid column by comma saparator and then search for facid.

SQL
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[ParseValues]
(@String varchar(8000), @Delimiter varchar(10) )
RETURNS @RESULTS TABLE (ID int identity(1,1), Val varchar(50))
AS
BEGIN
    DECLARE @Value varchar(100)
    WHILE @String is not null
    BEGIN
        SELECT @Value=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN LEFT(@String,PATINDEX('%'+@Delimiter+'%',@String)-1) ELSE @String END, @String=CASE WHEN PATINDEX('%'+@Delimiter+'%',@String) >0 THEN SUBSTRING(@String,PATINDEX('%'+@Delimiter+'%',@String)+LEN(@Delimiter),LEN(@String)) ELSE NULL END
        INSERT INTO @RESULTS (Val)
        SELECT @Value
    END
RETURN
END

query
SQL
select b.bthid, pv.val as facId
from bthfac b
cross apply dbo.ParseValues(facid,',') as pv
where pv.val=4

Happy Coding!
:)
 
Share this answer
 
v3
SQL
select Bthid from bthfac WHERE
      Facid LIKE '%,' + @search + ',%' --middle
      OR
      Facid LIKE @search + ',%' --start
      OR
      Facid LIKE '%,' + @search --end
      OR
      Facid =  @search --single 


For more info refer

http://stackoverflow.com/questions/5611715/where-value-in-column-containing-comma-delimited-values[^]
 
Share this answer
 
You need to use

SQL
where facid like '%4%'
 
Share this answer
 
v2
Comments
Aarti Meswania 26-Sep-13 1:09am    
when condition will be
where facid like '%1%'
it will show wrong data
You can try like given below -


select Bthid from bthfac where (Facid LIKE '4,%' OR FacID LIKE '4' or facID like '%,4,%)
 
Share this answer
 
Hi,

To get the answer as you mentioned change the query as follows,

select Bthid from batch where Facid like '%4%'

-- Mohamed Riswan
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900