我正在执行数据迁移到具有非常不同结构的新数据库。使用SQL Server& T-SQL。
这是我的表的一个SQLFiddle示例,到目前为止我已经到了: http://sqlfiddle.com/#!18/d179b/1
我有四张桌子:
CallNotes :
Id, uniqueidentifier
OldCallRecordId, int -- Used for migrating only, not in final
Content, nvarchar(100)
CallTopics :
Id, uniqueidentifier
Name, nvarchar(50)
CallNoteCallTopics :
CallNoteId, uniqueidentifier
CallTopicId, uniqueidentifier
OldCallRecords :
Id, int
CallTopicOne, bit
CallTopicTwo, bit
CallTopicThree, bit
CallTopicFour, bit
我想在true
声明中将CallTopic*
OldCallRecords
的所有CallNoteCallTopics.CallTopicId
INSERT
值转换为CASE
所有其他表格中都包含数据。
我目前正在尝试使用INSERT INTO CallNoteCallTopics
SELECT
CallNotes.Id,
CASE
WHEN OldCallRecords.CallTopicOne = 1
THEN (SELECT CallTopics.Id
FROM CallTopics
WHERE CallTopics.Name = 'Call Topic One')
WHEN OldCallRecords.CallTopicTwo = 1
THEN (SELECT CallTopics.Id
FROM CallTopics
WHERE CallTopics.Name = 'Call Topic Two')
WHEN OldCallRecords.CallTopicThree = 1
THEN (SELECT CallTopics.Id
FROM CallTopics
WHERE CallTopics.Name = 'Call Topic Three')
WHEN OldCallRecords.CallTopicFour = 1
THEN (SELECT CallTopics.Id
FROM CallTopics
WHERE CallTopics.Name = 'Call Topic Four')
END
FROM
OldCallRecords
LEFT JOIN
CallNotes ON CallNotes.OldCallRecordId = OldCallRecords.Id
语句,但这只会让我获得第一个真正的价值,这不是我想要的:
__init__(..)
答案 0 :(得分:1)
发生这种情况是因为当其中一个候选列点击对应CASE WHEN
然后输出时,将不会再次检查同一行。
您可以尝试使用UNION
INSERT INTO CallNoteCallTopics
SELECT
CallNotes.Id
,(SELECT CallTopics.Id FROM CallTopics WHERE CallTopics.Name = 'Call Topic One') as CallTopicId
FROM OldCallRecords
LEFT JOIN CallNotes
ON CallNotes.OldCallRecordId = OldCallRecords.Id
WHERE OldCallRecords.CallTopicOne = 1
UNION
SELECT
CallNotes.Id
,(SELECT CallTopics.Id FROM CallTopics WHERE CallTopics.Name = 'Call Topic Two') as CallTopicId
FROM OldCallRecords
LEFT JOIN CallNotes
ON CallNotes.OldCallRecordId = OldCallRecords.Id
WHERE OldCallRecords.CallTopicTwo = 1
UNION
SELECT
CallNotes.Id
,(SELECT CallTopics.Id FROM CallTopics WHERE CallTopics.Name = 'Call Topic Three') as CallTopicId
FROM OldCallRecords
LEFT JOIN CallNotes
ON CallNotes.OldCallRecordId = OldCallRecords.Id
WHERE OldCallRecords.CallTopicThree = 1
UNION
SELECT
CallNotes.Id
,(SELECT CallTopics.Id FROM CallTopics WHERE CallTopics.Name = 'Call Topic Four') as CallTopicId
FROM OldCallRecords
LEFT JOIN CallNotes
ON CallNotes.OldCallRecordId = OldCallRecords.Id
WHERE OldCallRecords.CallTopicFour = 1