New to SQL Server and I'm having a BLAST! Converting an Access database, and really enjoying the experience. Since I'm not the most experienced SQL guy yet, I was wondering what the best approach might be to this problem:
I have a simple query with four tables: tAGProjects, tProjectTypes, tProjectAgents and tAgents.
Often there are two or more agents on a project, and rather than returning multiple rows for a project when there are multiple agents, I'd like to gather all the agents into a comma separated variable and insert it into my returned recordset. Here's an example of the multiple records:
Project Type Created Agents
TestP Type1 1/1/2007 CT
TestP Type1 1/1/2007 MM
Here's an example of what I'd like to do:
Project Type Created Agents
TestP Type1 1/1/2007 CT,MM
My initial thoughts are to create a temp table, then populate it with the distinct records, then cycle through the distinct records (using a cursor?) and run a query that creates the comma separated variable and inserts it into the temp table.
Not sure this is the best way to go, since I've been told over and over again to avoid cursors at all costs. I just can't think of a better way to do it. Any suggestions?
I have a simple query with four tables: tAGProjects, tProjectTypes, tProjectAgents and tAgents.
Code:
SELECT tAGProjects.AGProjectKey, tAGProjects.ProjectTitle, tAGProjects.ClosedProject,
tAGProjects.Created, tProjectTypes.ProjectTypeDesc, tAgents.AgentName
FROM tAGProjects
LEFT JOIN tProjectAgents ON tAGProjects.AGProjectKey = tProjectAgents.AGProjectKey
LEFT JOIN tAgents ON tProjectAgents.AgentKey = tAgents.AgentKey
LEFT JOIN tProjectTypes ON tAGProjects.ProjectTypeKey = tProjectTypes.ProjectTypeKey
Often there are two or more agents on a project, and rather than returning multiple rows for a project when there are multiple agents, I'd like to gather all the agents into a comma separated variable and insert it into my returned recordset. Here's an example of the multiple records:
Project Type Created Agents
TestP Type1 1/1/2007 CT
TestP Type1 1/1/2007 MM
Here's an example of what I'd like to do:
Project Type Created Agents
TestP Type1 1/1/2007 CT,MM
My initial thoughts are to create a temp table, then populate it with the distinct records, then cycle through the distinct records (using a cursor?) and run a query that creates the comma separated variable and inserts it into the temp table.
Not sure this is the best way to go, since I've been told over and over again to avoid cursors at all costs. I just can't think of a better way to do it. Any suggestions?