SQL Query to update parent record with child record values

Posted by Wells on Super User See other posts from Super User or by Wells
Published on 2012-03-31T01:35:37Z Indexed on 2012/03/31 17:34 UTC
Read the original article Hit count: 355

Filed under:
|

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

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, ''))

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
)

© Super User or respective owner

Related posts about sql-server

Related posts about tsql