T-SQL将XML字符串转换为表数据

时间:2018-05-02 14:17:17

标签: sql sql-server xml tsql

我是将XML字符串转换为SQL Server表的新手。当我执行以下代码时,它会在Management Studio的结果窗口中生成表格数据。如果我尝试取消注释插入行,则查询错误输出。我创建的表格如下所示:

enter image description here

T-SQL就是这个(我不确定我做错了什么):

DECLARE @XML XML

SET @XML = '
    <Codes>
      <Code>
        <TranCode>09764812</TranCode>
        <TranDescr>WP FBCCP ADJUSTMENT</TranDescr>
        <PosTranCode>77724</PosTranCode>
        <NegTranCode>88820</NegTranCode>
      </Code>
      <Code>
        <TranCode>09764804</TranCode>
        <TranDescr>WP FBCCP CRM</TranDescr>
        <PosTranCode>77724</PosTranCode>
        <NegTranCode>88820</NegTranCode>
      </Code>
      <Code>
        <TranCode>09764804</TranCode>
        <TranDescr>WP FBCCP CRM</TranDescr>
        <PosTranCode>77724</PosTranCode>
        <NegTranCode>88820</NegTranCode>
      </Code>
    </Codes>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

--INSERT INTO 670_TransCodes (TranCode,TranDescr,PosTranCode,NegTranCode)
    SELECT TranCode,TranDescr,PosTranCode,NegTranCode
    FROM OPENXML(@handle, '/Codes/Code', 2)  
        WITH (
        TranCode varchar(20) 'TranCode',
        TranDescr varchar(50) 'TranDescr',
        PosTranCode INT 'PosTranCode',
        NegTranCode INT 'NegTranCode'
        )

    EXEC sp_xml_removedocument @handle 

1 个答案:

答案 0 :(得分:4)

您需要按[]

包围表格名称
INSERT INTO [670_TransCodes] (TranCode,TranDescr,PosTranCode,NegTranCode)

我会使用 xml node方法

INSERT INTO [670_TransCodes] (TranCode,TranDescr,PosTranCode,NegTranCode)
select a.value('TranCode[1]', 'varchar(20)') as TranCode,
       a.value('TranDescr[1]', 'varchar(50)') as TranDescr,
       a.value('PosTranCode[1]', 'INT') as TranDescr,
       a.value('NegTranCode[1]', 'INT')  as NegTranCode    
from @XML.nodes('/Codes/Code') as t(a);