Solved

SQL Query to update parent record with child record values

Posted on 2012-03-30
2
401 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:wells68
  • 2
2 Comments
 
LVL 2

Accepted Solution

by:
wells68 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:wells68
ID: 37793198
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

759 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now