我有一个必须格式化来自以下输出的XML结构的要求:
DECLARE @cousumptionFileName VARCHAR(50)
DECLARE @sqlCmd VARCHAR(1000)
DECLARE @sqlConStr VARCHAR(1000)
SET @cousumptionFileName = 'C:\export\IDE\Consumption.xml' -- SELECT * FROM ' + DB_NAME()+'.dbo.ReadingData
SET @sqlConStr = 'select top 10 * from [FixedNetworkist].[dbo].[ConsumptionReading0] order by deviceid FOR XML AUTO'
SET @sqlCmd = 'bcp "' + @sqlConStr + '" queryout ' + @cousumptionFileName + ' -w -T'
EXEC xp_cmdshell @sqlCmd
输出为:
<Reading0 RecordId="14452573" PartitionSequence="1" DeviceId="1015" DeviceType="13" CollectorId="74045037" CollectorType="120" Reading="0" ReadingDateTime="2019-01-21T01:15:00" PresentationInterval="15" RecordEpochTime="-599450337"/>
<Reading0 RecordId="14452859" PartitionSequence="1" DeviceId="1015" DeviceType="13" CollectorId="51000666" CollectorType="120" ChannelNumber="1" Reading="0" IntervalStatus="0" ReadingDateTime="2019-01-21T01:15:00" PresentationInterval="15" RecordEpochTime="-599450335"/>
我希望它具有避免重复值的结构:
<Reading0 PartitionSequence="1" DeviceId="1015" DeviceType="13" ChannelNumber="1" >
<Readings>
<Reading RecordId="14452573" CollectorId="74045037" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
<Reading RecordId="14452859" CollectorId="51000666" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
</Readings>
有人可以帮助我实现这一目标吗?
答案 0 :(得分:0)
为进行转换,请考虑使用“ FOR XML EXPLICIT”,而不是“ FOR XML AUTO”。好文章,以了解更多有关: https://docs.microsoft.com/en-us/sql/relational-databases/xml/use-explicit-mode-with-for-xml?view=sql-server-2017
我的样本数据:
DECLARE @Reading TABLE ( PartitionSequence int, DeviceId int, DeviceType int, ChannelNumber int,CollectorId int,RecordId int, Reading int, ReadingDateTime datetime, RecordEpochTime int)
INSERT INTO @Reading ( PartitionSequence, DeviceId , DeviceType, ChannelNumber,CollectorId , RecordId, Reading, ReadingDateTime, RecordEpochTime )
VALUES
(1,1015,13,1,1,14452573,0,'2019-01-21T00:29:58',-599453037)
,(1,1015,13,1,1,51000666,0,'2019-01-21T00:29:58',-599453037)
SQL查询:
SELECT
1 AS Tag
,NULL AS parent
,r.PartitionSequence AS [Readings!1!PartitionSequence]
,r.DeviceId AS [Readings!1!DeviceId]
,r.DeviceType AS [Readings!1!DeviceType]
,r.ChannelNumber AS [Readings!1!ChannelNumber]
,NULL AS [Reading!2!RecordId]
,NULL AS [Reading!2!Reading]
,NULL AS [Reading!2!ReadingDateTime]
,NULL AS [Reading!2!RecordEpochTime]
FROM @Reading r
UNION
SELECT
2 AS Tag
,1 AS parent
,r.PartitionSequence
,r.DeviceId
,r.DeviceType
,r.ChannelNumber
,r.RecordId
,r.Reading
,r.ReadingDateTime
,r.RecordEpochTime
FROM @Reading r
FOR XML EXPLICIT
查询结果:
<Readings PartitionSequence="1" DeviceId="1015" DeviceType="13" ChannelNumber="1">
<Reading RecordId="14452573" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
<Reading RecordId="51000666" Reading="0" ReadingDateTime="2019-01-21T00:29:58" RecordEpochTime="-599453037" />
</Readings>