-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUpdateReferences.sql
68 lines (63 loc) · 2.6 KB
/
UpdateReferences.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
--------------------------------------------------------------------------------------------------------------------------------
-- UPDATE REFERENCES
--------------------------------------------------------------------------------------------------------------------------------
-- Saves the 1:1 mappings for referenced topics.
--------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[UpdateReferences]
@TopicID INT,
@ReferencedTopics TopicReferences READONLY ,
@Version DATETIME2(7) = NULL ,
@DeleteUnmatched BIT = 0
AS
--------------------------------------------------------------------------------------------------------------------------------
-- SET DEFAULT VERSION DATETIME
--------------------------------------------------------------------------------------------------------------------------------
IF @Version IS NULL
SET @Version = SYSUTCDATETIME()
--------------------------------------------------------------------------------------------------------------------------------
-- INSERT NOVEL VALUES
--------------------------------------------------------------------------------------------------------------------------------
INSERT
INTO TopicReferences (
Source_TopicID,
ReferenceKey,
Target_TopicID,
Version
)
SELECT @TopicID,
New.ReferenceKey,
New.TopicID,
@Version
FROM @ReferencedTopics New
OUTER APPLY (
SELECT TOP 1
Target_TopicID AS ExistingValue
FROM TopicReferences
WHERE Source_TopicID = @TopicID
AND ReferenceKey = New.ReferenceKey
ORDER BY Version DESC
) Existing
WHERE ISNULL(ExistingValue, '') != New.TopicID
AND New.TopicID > 0
--------------------------------------------------------------------------------------------------------------------------------
-- DELETE UNMATCHED VALUES
--------------------------------------------------------------------------------------------------------------------------------
IF @DeleteUnmatched = 1
BEGIN
INSERT
INTO TopicReferences
SELECT @TopicID,
Existing.ReferenceKey,
NULL,
@Version
FROM @ReferencedTopics New
RIGHT JOIN ReferenceIndex Existing
ON Source_TopicID = @TopicID
AND Existing.ReferenceKey = New.ReferenceKey
WHERE Source_TopicID = @TopicID
AND ISNULL(TopicID, '') = ''
END
--------------------------------------------------------------------------------------------------------------------------------
-- RETURN TOPIC ID
--------------------------------------------------------------------------------------------------------------------------------
RETURN @TopicID;