I have a table of pending changes, and I am trying to apply the changes to a view so I can see up-to-date data.
First some background: I have a website that allows simple changes to data in Project Web Access (PWA). An issue with PWA is that you can't change the data directly in its database, so I use SharePoint's CSOM to checkout, modify, check-in, publish and save changes to projects and tasks. This takes 10-20 seconds which is too slow for the user experience on the website.
I've worked around this by writing modified fields to a pending changes table, i.e. the identifier for the row, the field changed and the new value. I currently merge these changes in c# .Net (RBAR) for the website to display.
I would like to merge this data in SQL server, and preferably not row by row.
I'm testing in here
WITH
SourceDataView (id, name, age, joined) AS
(
SELECT 1, 'John' , 45, Cast('2018-01-15' as DateTime) UNION
SELECT 2, 'Paul', 33, Cast('2018-02-08' as DateTime) UNION
SELECT 3, 'George', 39, Cast('2018-03-29' as DateTime)
),
PendingChanges (id, foreignId, fieldName, fieldValue) AS
(
SELECT 1, 2, 'name', 'Peter' UNION
SELECT 2, 1, 'age', '34' UNION
SELECT 3, 3, 'joined', '2018-02-22' UNION
SELECT 4, 1, 'joined', '2018-01-10' UNION
SELECT 5, 3, 'joined', '2017-12-30'
)
-- Just show the joined data
SELECT * FROM
SourceDataView s
LEFT JOIN
PendingChanges p
on s.id = p.foreignId
ORDER BY p.id;
-- This is what I am expecting
WITH
DesiredResultsView (id, name, age, joined) AS (
SELECT 1, 'John' , 34, Cast('2018-01-10' as DateTime) UNION
SELECT 2, 'Peter', 33, Cast('2018-02-08' as DateTime) UNION
SELECT 3, 'George', 39, Cast('2017-12-30' as DateTime)
) SELECT * from DesiredResultsView
A couple of caveats, if the data is changed twice the last edit wins. Also, the data types need to properly converted.