I'm creating a stored procedure that will return a grouping of details about my database. Part of this SP needs to contain a concatenated list of Groups for a User (a user can belong to many groups). The best practice is to create a temporary table and populate it with group listings as an initial step, then join it up later to return as a large result set for my SP.
I have a table called UserGroup as follows:
CREATE TABLE UserGroup
(
UserID uniqueidentifier not null,
GroupID uniqueidentifier not null
)
There's another table, [Group]. It has a GroupName and Description for each GroupID. Then, there's a table called [User] that has a UserID attached to each UserName and user detail columns.
I want to do SOMETHING like this:
INSERT INTO #storegroupdata
(OwnerID, GroupList)
select B.UserID, @temp = COALESCE(@temp + ',', '') + CAST(g.GroupName as nvarchar(200))
from appSec.dbo.UserGroup ug
inner join appSec.dbo.[Group] g on g.GroupID = ug.GroupID
inner join app.dbo.User B on B.UserID = ug.UserID
Obviously, it's psuedocode, because you can't select a variable in the same step you perform data-retrieval (and @temp needs to be cleared after each list is successfully created). But I want to create a temporary table full of concatenated lists...Is this possible without using frowned upon, performance nightmare methods?
The only alternatives I know of are subqueries and cursors. I could have a subquery select the group list for each user -- but this has extremely, extremely harsh performance concerns. I would know, since I have a working version of this that's too slow; it's not a solution. Using a cursor is just about as bad.
Is there a technique I'm not aware of for dealing with a situation like this? Or am I forced to rely on a cursor or subquery to create a list for each user in my database? I also don't want to create any additional procedures or functions to solve this, I'd like one stored procedure to be able to handle everything.