Solved

SQL Query to update parent record with child record values

Posted on 2012-03-30
2
472 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 3

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 3

Author Closing Comment

by:Wells Anderson
ID: 37793198
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Time out only from one specific computer client 15 53
Remove () 10 41
SQL Server Database Inventory 7 30
SQL: get ride of blank rows 11 23
Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

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