3

I have one table like

tbl

---------------------
id  users   name
---------------------
1   2,3     acc1
2   4       acc2
3   2,4,1   acc3
4   4,1     acc4

In this table I want to get id and name by users i.e user [2] have which id and name

Suppose I pass user [2] then i get result id is 1 and 3 and name acc1 and acc3.

1

4 Answers 4

1

Try this will work for you

    SELECT id,name FROM yourtablename WHERE `users` LIKE '%2%'; 
Sign up to request clarification or add additional context in comments.

1 Comment

For the usecase, where "users" column have value 20, 200, etc. Your SQL will fail the test case.
1

You can split those comma separated values using XML functions and then search in the result :

DECLARE @table TABLE(id  INT, users   VARCHAR(30), name VARCHAR(30))
INSERT INTO @table VALUES
(1,'2,3','acc1'),
(2,'4','acc2'),
(3,'2,4,1','acc3'),
(4,'4,1','acc4')


SELECT t.id,
       t.name,
       ( c1.value('.', 'varchar(100)') )
FROM   (SELECT id,
               name,
               CAST('<N>' + REPLACE(users, ',', '</N><N>') + '</N>' AS XML)
        FROM   @table) t(id, name, c)
       CROSS APPLY c.nodes('/N') AS t1(c1)
WHERE  ( c1.value('.', 'varchar(100)') ) = '2' 

Comments

0

Use the LIKE function

SELECT id, name
FROM yourtable
WHERE (user = '2' OR user LIKE '2,%' OR user LIKE '%,2' OR user LIKE '%,2,%')

8 Comments

what if, data 200 present in users instead of 2,3?
@Matt this is no longer needed (OR user LIKE '%,2,%')
@MAC it is if user is 1,2,3
the (user LIKE '%2,%') or (user LIKE '%,2%') will do @Matt it will still give the result of 2 even when it is in the middle
This is a bad solution. The correct method is to split the values down first. The values shouldn't be stored as a delimited string in the first place for this very reason. See my answer.
|
0

You shouldn't store delimited values in a database, but here's a solution for you, that will normalise the data:

;WITH CTE AS (
SELECT T1.[id], T2.my_Splits AS [user], T1.[name]
FROM (
  SELECT *,CAST('<X>'+replace(T.users,',','</X><X>')+'</X>' as XML) as my_Xml 
  FROM Table1 T
 ) T1
 CROSS APPLY ( 
 SELECT my_Data.D.value('.','varchar(50)') as my_Splits
 FROM T1.my_Xml.nodes('X') as my_Data(D)) T2)
SELECT *
FROM CTE
WHERE [user] = 2

And a working fiddle: http://sqlfiddle.com/#!6/dcec6/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.