我有一个 sql 脚本,可以在数据库 (tmp1) 中加载 xml 的文件名。
列表如下所示:
20130918_0932_ZSK40-2.xml
20130918_1032_ZSK70.xml
20130921_0532_ZSK40-2.xml
在另一个脚本中,我想加载每个 xml 文件,以便可以将其导入数据库。
我需要的是选择 tmp1 中的第一个文件名来加载它。
加载文件的脚本部分如下所示:
SELECT CAST(XmlContent AS XML)
FROM OPENROWSET(
BULK 'C:\20130921_0532_ZSK40-2.xml',
SINGLE_BLOB) AS T(XmlContent)
) AS T(XmlContent)
它应该是什么样子?
提前致谢,
IF OBJECT_ID('tempdb..#tmpTable') IS NOT NULL
DROP TABLE #tmpTable
SELECT machine = XmlContent.value('(/recordedData/machine)[1]', 'varchar(50)'),
RecordingDate = XmlContent.value('(/recordedData/date)[1]', 'varchar(50)'),
RecordingTime = XmlContent.value('(/recordedData/hour)[1]', 'varchar(50)'),
VariableName = XVar.value('(Name)[1]', 'varchar(50)'),
VariableValue = XVar.value('(Value)[1]', 'varchar(50)')
Into #tmpTable
FROM (
SELECT CAST(XmlContent AS XML)
FROM OPENROWSET(
BULK 'C:\xml_path_here.xml',
SINGLE_BLOB) AS T(XmlContent)
) AS T(XmlContent)
CROSS APPLY
XmlContent.nodes('/recordedData/CollectedData/variable') AS XTbl(XVar)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.VariableName)
FROM #tmpTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT machine, RecordingDate, RecordingTime, ' + @cols + ' from
(
select machine
, RecordingDate
, RecordingTime
, VariableName
, VariableValue
from #tmpTable
) x
pivot
(
max(VariableValue)
for VariableName in (' + @cols + ')
) p '
execute(@query)
--SELECT * FROM #tmpTable
drop table #tmpTable