Solved

SQL Query to update parent record with child record values

Posted on 2012-03-30
2
449 Views
Last Modified: 2012-06-21
I need to create a Trigger that fires when a child record (Codes) is added, updated or deleted. The Trigger stuffs a string of comma separated Code values from all child records (Codes) into a single field in the parent record (Projects) of the added, updated or deleted child record.

I am stuck on writing a correct query to retrieve the Code values from just those child records that are the children of a single parent record.
 -- Create the test tables
CREATE TABLE projects (
  ProjectId varchar(16) PRIMARY KEY,
  ProjectName varchar(100),
  Codestring nvarchar(100)
)
GO
CREATE TABLE prcodes (
  CodeId varchar(16) PRIMARY KEY,
  Code varchar (4),
  ProjectId varchar(16)
)
GO
-- Add sample data to tables: Two projects records, one with 3 child records, the other with 2.
INSERT INTO projects
(ProjectId, ProjectName)
SELECT '101','Smith' UNION ALL
SELECT '102','Jones'
GO
INSERT INTO prcodes
(CodeId, Code, ProjectId)
SELECT 'A1','Blue', '101' UNION ALL
SELECT 'A2','Pink', '101' UNION ALL
SELECT 'A3','Gray', '101' UNION ALL
SELECT 'A4','Blue', '102' UNION ALL
SELECT 'A5','Gray', '102'
GO

Open in new window

I am stuck on how to create a correct Update query.
Can you help fix this query?
-- Partially working, but stuffs all values, 
-- not just values from chile (prcodes) records of parent (projects)
UPDATE proj
SET
proj.Codestring = (SELECT STUFF((SELECT ',' + prc.Code 
FROM projects proj INNER JOIN prcodes prc ON proj.ProjectId = prc.ProjectId
ORDER BY 1 ASC FOR XML PATH('')),1, 1, ''))

Open in new window

The result I get for the Codestring field in Projects is:
ProjectId      ProjectName      Codestring
101            Smith            Blue,Blue,Gray,Gray,Pink
...

But the result I need for the Codestring field in Projects is:
ProjectId      ProjectName      Codestring
101            Smith            Blue,Pink,Gray

Here is my start on the Trigger. The Update query, above, will be added to this Trigger. Can you help me complete the Trigger creation query?
CREATE TRIGGER Update_Codestring ON prcodes
AFTER INSERT, UPDATE, DELETE
AS
WITH CTE AS (
  select ProjectId from inserted
  union
  select ProjectId from deleted
)

Open in new window

Thank you!  (Cross-posted to StackExchange.com - I will award points here in any case.)
0
Comment
Question by:Wells Anderson
  • 2
2 Comments
 
LVL 2

Accepted Solution

by:
Wells Anderson earned 0 total points
ID: 37793182
The question was answered perfectly on StackExchange yesterday. Here is the solution:

The following trigger will perform as you want.

CREATE TRIGGER Update_Codestring ON prcodes
AFTER INSERT, UPDATE, DELETE
AS
UPDATE projects
SET Codestring = (SELECT STUFF((SELECT ',' + prc.Code 
    FROM projects proj INNER JOIN prcodes prc ON proj.ProjectId = prc.ProjectId
    WHERE proj.ProjectId = projects.ProjectId
    ORDER BY 1 ASC FOR XML PATH('')),1, 1, ''))
where ProjectId in (SELECT ProjectId FROM inserted
                    UNION
                    SELECT ProjectId FROM deleted)

Open in new window

What you were missing in your original update statement was:

WHERE proj.ProjectId = projects.ProjectId - This will filter the subquery to only the project that is being updated. projects with no alias comes from the update statement so as update is applied against each row in projects only the current project row being updated.

WHERE ProjectId IN (SELECT ProjectId FROM inserted UNION SELECT ProjectId FROM deleted) - This will filter the update to affect only the rows with changed children.

Also you can simplify the update statement since it doesn't need the projects table included twice:

CREATE TRIGGER Update_Codestring ON prcodes
AFTER INSERT, UPDATE, DELETE
AS
UPDATE projects
SET Codestring = (SELECT STUFF((SELECT ',' + prc.Code 
    FROM prcodes prc
    WHERE prc.ProjectId = projects.ProjectId
    ORDER BY 1 ASC FOR XML PATH('')),1, 1, ''))
WHERE ProjectId IN (SELECT ProjectId FROM inserted
                    UNION
                    SELECT ProjectId FROM deleted)

Open in new window

Finally do you really need to store the Codestring on your Projects table? It's something that can easily be recalculated in a query at anytime or even put into a view. That was you don't have to worry about having to store the extra data and have a trigger to maintain it.
0
 
LVL 2

Author Closing Comment

by:Wells Anderson
ID: 37793198
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question