我一直在使用XML将大量数据导入SQL一段时间,但我想知道是否可以从具有子节点的单个XML文件中跨多个表导入数据?
给出这个例子:
DECLARE @tbl_makes TABLE (ID int IDENTITY(1,1), makeName nvarchar(100))
INSERT INTO @tbl_makes (makeName) VALUES ('Ford')
INSERT INTO @tbl_makes (makeName) VALUES ('Jaguar')
DECLARE @tbl_models TABLE (ID int IDENTITY(1,1), makeID int, modelName nvarchar(100))
INSERT INTO @tbl_models (makeID, modelName) VALUES (1, 'Escort')
INSERT INTO @tbl_models (makeID, modelName) VALUES (1, 'Sierra')
INSERT INTO @tbl_models (makeID, modelName) VALUES (2, 'XK')
INSERT INTO @tbl_models (makeID, modelName) VALUES (2, 'XJS')
SELECT * FROM @tbl_makes m INNER JOIN @tbl_models md ON m.ID = md.makeID
DECLARE @xml XML = '
<cars>
<make name="Ford">
<model name="Mustang" />
<model name="Taurus" />
<model name="F350" />
</make>
<make name="Aston Martin">
<model name="Vanquish" />
<model name="DB7" />
<model name="Lagonda" />
</make>
</cars>'
我很欣赏在插入相关数据之前需要先插入/查找制作名称。我在网上搜索了这个答案,但是示例只使用一个表。我猜这不可能没有使用各种临时表,但这里有......
答案 0 :(得分:6)
这样的解决方案怎么样?
INSERT INTO @tbl_makes (makeName)
SELECT i.i.value('@name', 'nvarchar(100)')
FROM @xml.nodes('/cars[1]/make')i(i)
LEFT JOIN @tbl_makes MA on i.i.value('@name', 'nvarchar(100)') = MA.makeName
WHERE MA.ID IS NULL;
INSERT INTO @tbl_models (makeID, modelName)
SELECT MA.ID, j.j.value('@name', 'nvarchar(100)')
FROM @xml.nodes('/cars[1]/make')i(i)
INNER JOIN @tbl_makes MA ON i.i.value('@name', 'nvarchar(100)') = MA.makeName
CROSS APPLY i.i.nodes('model')j(j)
LEFT JOIN @tbl_models MO on j.j.value('@name', 'nvarchar(100)') = MO.modelName
WHERE MO.ID IS NULL;