-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUpdateAttributes.sql
62 lines (58 loc) · 2.38 KB
/
UpdateAttributes.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
--------------------------------------------------------------------------------------------------------------------------------
-- UPDATE ATTRIBUTES
--------------------------------------------------------------------------------------------------------------------------------
-- Saves a set of AttributeValues to the Attributes table, while optionally accounting for deleted or unmatched attributes.
-- Optionally update ExtendedAttributes values if XML is included.
--------------------------------------------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[UpdateAttributes]
@TopicID INT,
@Attributes AttributeValues READONLY ,
@Version DATETIME2(7) = NULL ,
@DeleteUnmatched BIT = 0
AS
--------------------------------------------------------------------------------------------------------------------------------
-- INSERT NEW ATTRIBUTES
--------------------------------------------------------------------------------------------------------------------------------
INSERT
INTO Attributes (
TopicID ,
AttributeKey ,
AttributeValue ,
Version
)
SELECT @TopicID,
AttributeKey,
ISNULL(AttributeValue, ''),
@Version
FROM @Attributes New
OUTER APPLY (
SELECT TOP 1
AttributeValue AS ExistingValue
FROM Attributes
WHERE TopicID = @TopicID
AND AttributeKey = New.AttributeKey
ORDER BY Version DESC
) Existing
WHERE ISNULL(ExistingValue, '') != ISNULL(AttributeValue, '')
--------------------------------------------------------------------------------------------------------------------------------
-- DELETE UNMATCHED ATTRIBUTES
--------------------------------------------------------------------------------------------------------------------------------
IF @DeleteUnmatched = 1
BEGIN
INSERT
INTO Attributes
SELECT @TopicID,
Existing.AttributeKey,
'',
@Version
FROM AttributeIndex Existing
LEFT JOIN @Attributes New
ON Existing.TopicID = @TopicID
AND Existing.AttributeKey = New.AttributeKey
WHERE ISNULL(New.AttributeKey, '') = ''
AND Existing.TopicID = @TopicID
END
--------------------------------------------------------------------------------------------------------------------------------
-- RETURN TOPIC ID
--------------------------------------------------------------------------------------------------------------------------------
RETURN @TopicID;