1

I have following Table

Table User
UserID         Name
1              Om
2              John
3              Kisan
4              Lisa
5              Karel

Table Game
Games          Players
Golf           1,3,5
Football       4

I wrote query:

Select UserId, 
Name from User 
Where UserID IN 
    (Select Players from Game where Games='Golf')

Result:
~~~~~~~
0 Rows

Above query does not return me any result while it works well when i directly specify values for In clause in statement.

Select UserId, Name 
from User 
Where UserID IN (1,3,5)

Result:
~~~~~~~
UserID         Name
1              Om
3              Kisan
5              Karel
3 rows

However when I change the condition in very 1st query with Football:

Select UserId, Name 
from User 
Where UserID IN 
    (Select Players 
     from Game 
     where Games='Football'). 

This returns me following result:

UserID         Name
4              Lisa
1 row

How I can work around so that my very 1st query returns me the right result?

I think I'm in wrong direction. Help me out!

BlackVegetable
  • 12,594
  • 8
  • 50
  • 82

3 Answers3

5

This is what you get for storing comma separated values in a field. Now you have to split it, using, say this function and do something like

Select User.UserId, User.Name from User 
inner join splitstring((Select Players from Game where Games='Golf')) a
on User.UserID = a.Name

But consider changing your table "Game" design to

Games          Players
Golf           1
Golf           3
Golf           5
Football       4

Then you can do simple

Select User.UserId, User.Name
from User inner join Game
on User.UserID = Game.Players
Where Game.Games = 'Golf'

without any additional functions.

Community
  • 1
  • 1
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
2

Your first query translates to this:

Select UserId, Name 
from User 
Where UserID IN (`1,3,5`)

Notice that it is a string representation of the IDs, not a comma separated list like in your second query.

There are many Split functions out there written for this very scenario.

You can utilize one of them as such:

DECLARE @PlayersCsv NVARCHAR(MAX)
Select @PlayersCsv = Players from Game where Games='Golf'

Select UserId, 
Name from User 
Where UserID IN 
    (Select Value FROM dbo.Split(@PlayersCsv, ','))
Khan
  • 17,904
  • 5
  • 47
  • 59
0
DECLARE @xml AS xml
SET @xml = (SELECT cast('<X>'+(''+replace(players,',' ,'</X><X>')+'</X>') AS xml)
            FROM Game WHERE Games='Golf')
SELECT UserId, Name 
FROM User
WHERE UserID IN
(SELECT N.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as T(N))

SQL Fiddle Results:

| USERID |  NAME |
|--------|-------|
|      1 |    Om |
|      3 | Kisan |
|      5 | Karel |
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30