在SQL Server

时间:2015-06-03 07:57:40

标签: sql-server

我有两张桌子,一张卡片,上面附有一张CardLines列表

Card (Unique: Code, Key)
----
Id | Code | Key

CardLine (FK: CardId, Unique: CardId, SubKey)
----
ID | CardId | Value | SubKey

考虑一些数据

Card
----
ID | CODE | Key
1  | C1   | K1
2  | C2   | K1
3  | C3   | K2

CardLine
----
ID | CardId | Value | SubKey
1  | C1     | 10    | SK1
2  | C1     | 20    | SK2
3  | C2     | 30    | SK1
4  | C2     | 40    | SK3
5  | C3     | 50    | SK4

这里,在Card表中,C2现在需要转换为C1(因为C2是错误的条目,它应该是C1)。为此,我尝试编写MERGE查询,如果匹配,我需要运行子查询以合并每个匹配的CardLines。像(伪代码)

的东西
MERGE into Card as target
USING (SELECT ID, Code, Key from Card where Code = 'C2')
ON (target.Code = 'C1' and target.Key = K1)
WHEN MATCH
THEN
-- Merge the Cardlines in a similar mananner for a matched card (subquery?) - basically
-- Delete Card if no more lines assigned to it after merge
WHEN NOT MATCH
-- just update the Code from C2 -> C1

所需的输出

Card
----
ID | CODE | Key
1  | C1   | K1
3  | C3   | K2

CardLine
----
ID | CardId | Value | SubKey
1  | C1     | 40    | SK1   <-- merge of CardLine Id=1 and ID = 3, then 3 deleted
2  | C1     | 20    | SK2
4  | C1     | 40    | SK3   <-- no merge required, only product code update to C1 from C2
5  | C3     | 50    | SK4

我不是SQL专家(.Net),所以如果这不是正确的方法,会欣赏任何正确的方向

0 个答案:

没有答案