Lets say I have 2 tables:
1 with users and another one which keeps record of which users used what codes.
Users ----- Id, Name 1, 'John' 2, 'Doe' Codes ------ Id, UserId, code 1, 1, 145 2, 1, 187 3, 2, 251
Now I want to pull a query that results he following
Name, UsedCodes 'John', '145,187' 'Doe', '251'
How can this be done with a query or stored procedure?
For SQL Server as a really quick and dirty you could use a SQL function and a cursor. I would not really recommend this for high usage and I'll be really embarassed when someone points out a much easier example that doesn't need a function let alone a cursor.
And the function would be something like
EDIT: Sorry for any SQL Syntax errors, don't have SQL installed here to validate, etc. so done from memory.
Since you haven't specified the DB I'm giving you two options:MySql
With MySql you should simply use
GROUP_CONCAT()
aggregate function.Microsoft SQL Server 2005+
Obviously the fastest way (no cursors, no coalesce...) of getting the same result on MS DB is by using
FOR XML PATH('')
that simply omits XML elements.Other alternatives
Read this article, that explains all the possible ways of achieving this goal.