从SQL数据创建XML

时间:2014-08-06 18:52:31

标签: sql xml sql-server-2008 ssis

我有一个巨大的XML,有超过150个元素和属性。我需要使用来自SQL Server 2008表的数据填充少数(5或6)元素。这个创建的xml需要传递给webservice(到ESB),这必须按照每日计划进行。

我认为,在此处使用XML Path来创建XML并使用SSIS是没有意义的。任何人都可以建议一种方法吗?

这是示例XML。我只需要填写名称,地址和一些ID

<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName></FirstName>
        <LastName></LastName>
        <Gender></Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
    <CustomerData>
    </CustomerData>
</Customer>

2 个答案:

答案 0 :(得分:0)

一种方法是获取XML文档的空版本并将其分配给NVARCHAR(MAX)变量。对于要填充的每个节点或参数,请放置“标记”并使用替换函数填充该值。例如:

DECLARE @xml NVARCHAR(MAX)

SET @xml = N'<Company name="~company_name~">
<Department name="~dept_name~">
<Employee name="~employee_name~" title="~employee_title~" />
</Department>
</Company>'

SET @xml = REPLACE(@xml,N'~company_name~','Microsoft')
SET @xml = REPLACE(@xml,N'~dept_name~','Executive')
SET @xml = REPLACE(@xml,N'~employee_name~','Satya Nadella')
SET @xml = REPLACE(@xml,N'~employee_title~','CEO')

SELECT CAST(@xml AS XML)

这是一种更传统的方法。您需要在要更新的单元格中使用任意值:

DECLARE @example_data TABLE 
(FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Gender CHAR(1) NOT NULL,
City VARCHAR(255) NOT NULL,
[State] CHAR(2) NOT NULL)

INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Satya' , -- FirstName - varchar(255)
          'Nadella' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Redmond' , -- City - varchar(255)
          'WA'  -- State - char(2)
        )
INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Larry' , -- FirstName - varchar(255)
          'Ellison' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Woodside' , -- City - varchar(255)
          'CA'  -- State - char(2)
        )


DECLARE 
@customer_xml XML,
@xml XML,
@temp NVARCHAR(255),
@FirstName VARCHAR(255),
@LastName  VARCHAR(255),
@Gender CHAR(1),
@City VARCHAR(255),
@State CHAR(2)

SET @customer_xml = '<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName>a</FirstName>
        <LastName>b</LastName>
        <Gender>c</Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City>d</City>
                <State>e</State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
</Customer>'

DECLARE xml_cursor CURSOR FOR
SELECT FirstName , LastName , Gender , City , [State]
FROM @example_data

OPEN xml_cursor 

FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State

WHILE @@fetch_status = 0
BEGIN
    SET @xml = @customer_xml

    SET @xml.modify('
    replace value of (/Customer/CustomerData/FirstName[1]/text())[1]
    with sql:variable("@FirstName")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/LastName[1]/text())[1]
    with sql:variable("@LastName")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Gender[1]/text())[1]
    with sql:variable("@Gender")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Addresses/BillingAddress/City[1]/text())[1]
    with sql:variable("@City")
  ')

    SET @xml.modify('
    replace value of (/Customer/CustomerData/Addresses/BillingAddress/State[1]/text())[1]
    with sql:variable("@State")
  ')


    select @xml

    FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State
END

此方法不需要更新节点中的值。它只是插入一个新节点,然后删除旧节点:

DECLARE @example_data TABLE 
(FirstName VARCHAR(255) NOT NULL,
LastName VARCHAR(255) NOT NULL,
Gender CHAR(1) NOT NULL,
City VARCHAR(255) NOT NULL,
[State] CHAR(2) NOT NULL)

INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Satya' , -- FirstName - varchar(255)
          'Nadella' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Redmond' , -- City - varchar(255)
          'WA'  -- State - char(2)
        )
INSERT INTO @example_data
        ( FirstName , LastName , Gender , City , [State])
VALUES  ( 'Larry' , -- FirstName - varchar(255)
          'Ellison' , -- LastName - varchar(255)
          'M' , -- Gender - char(1)
          'Woodside' , -- City - varchar(255)
          'CA'  -- State - char(2)
        )


DECLARE 
@customer_xml XML,
@xml XML,
@temp NVARCHAR(255),
@FirstName VARCHAR(255),
@LastName  VARCHAR(255),
@Gender CHAR(1),
@City VARCHAR(255),
@State CHAR(2)

SET @customer_xml = '<?xml version="1.0" encoding="UTF-8"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customer.xsd">
<CustomerData>
        <StoreID></StoreID>
        <FirstName></FirstName>
        <LastName></LastName>
        <Gender></Gender>
        <BirthMonth></BirthMonth>
        <BirthYear></BirthYear>
        <BirthDay></BirthDay>
        <IsEmployee></IsEmployee>
        <customerID></customerID>
        <EmailAddress></EmailAddress>
        <PhoneNumber></PhoneNumber>
        <EmailSignUp></EmailSignUp>
        <CatalogSignup></CatalogSignup>
        <Addresses>
            <BillingAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </BillingAddress>
            <CatalogSignupAddress>
                <Address1></Address1>
                <Address2></Address2>
                <Address3></Address3>
                <City></City>
                <State></State>
                <ZipCode></ZipCode>
                <Fax1></Fax1>
            </CatalogSignupAddress>
            <StoredAddresses>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
                <StoredAddress>
                    <Address1></Address1>
                    <Address2></Address2>
                    <Address3></Address3>
                    <City></City>
                    <State></State>
                    <ZipCode></ZipCode>
                    <Fax1></Fax1>
                </StoredAddress>
            </StoredAddresses>
        </Addresses>
        <Hobbies_Enjoys>
            <Hobby></Hobby>
            <Enjoy></Enjoy>
        </Hobbies_Enjoys>
        <FavoriteFossilProducts>
            <ProductType></ProductType>
            <ProductType></ProductType>
        </FavoriteFossilProducts>
        <AgeRange></AgeRange>
        <PreferredEmailFormat></PreferredEmailFormat>
        <SavedCreditCards>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
            <CreditCard>
                <AcctNum></AcctNum>
                <ExpiryDate></ExpiryDate>
            </CreditCard>
        </SavedCreditCards>
        <PurchasedProductList>
            <SKU></SKU>
            <SKU></SKU>
        </PurchasedProductList>
        <OrderHistory>
            <Orders>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
                <Order>
                    <Number></Number>
                    <TotalAmount></TotalAmount>
                    <Promotion></Promotion>
                    <TimePlaced></TimePlaced>
                </Order>
            </Orders>
        </OrderHistory>
        <WishLists>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
            <WishList>
                <Name></Name>
                <Description></Description>
                <DateCreated></DateCreated>
                <LastUpdate></LastUpdate>
                <IsDefault></IsDefault>
                <Items>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                    <Item>
                        <Quantity></Quantity>
                        <PartNumber></PartNumber>
                        <DateCreated></DateCreated>
                        <LastUpdate></LastUpdate>
                    </Item>
                </Items>
            </WishList>
        </WishLists>
    </CustomerData>
</Customer>'

DECLARE xml_cursor CURSOR FOR
SELECT FirstName , LastName , Gender , City , [State]
FROM @example_data

OPEN xml_cursor 

FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State

WHILE @@fetch_status = 0
BEGIN
    SET @xml = @customer_xml

    SET @xml.modify('
    insert <FirstName>{ xs:string(sql:variable("@FirstName")) }</FirstName>          
    before (/Customer/CustomerData/FirstName)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/FirstName[2]
    ')

    SET @xml.modify('
    insert <LastName>{ xs:string(sql:variable("@LastName")) }</LastName>          
    before (/Customer/CustomerData/LastName)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/LastName[2]
    ')

    SET @xml.modify('
    insert <Gender>{ xs:string(sql:variable("@Gender")) }</Gender>          
    before (/Customer/CustomerData/Gender)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Gender[2]
    ')

    SET @xml.modify('
    insert <City>{ xs:string(sql:variable("@City")) }</City>          
    before (/Customer/CustomerData/Addresses/BillingAddress/City)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Addresses/BillingAddress/City[2]
    ')

    SET @xml.modify('
    insert <State>{ xs:string(sql:variable("@State")) }</State>          
    before (/Customer/CustomerData/Addresses/BillingAddress/State)[1]
    ')

    SET @xml.modify('
    delete /Customer/CustomerData/Addresses/BillingAddress/State[2]
    ')

    select @xml

    FETCH NEXT FROM xml_cursor into @FirstName, @LastName, @Gender, @City, @State
END

答案 1 :(得分:0)

您还可以使用FLWOR,它允许您通过使用模板一次生成xml,并仅将数据添加到您想要的元素。 您不需要创建表或存储过程。例如:

declare @x xml
set @x=(select FirstName, LastName from kc_consumer for xml path('CustomerData'))

SELECT @x.query('
for $a in /CustomerData
  return 
<CustomerData>
<StoreID></StoreID>

<FirstName>{data($a/FirstName)}</FirstName>
<LastName>{data($a/LastName)}</LastName>

<Gender></Gender>
<BirthMonth></BirthMonth>
<BirthYear></BirthYear>
<BirthDay></BirthDay>
<IsEmployee></IsEmployee>
<customerID></customerID>
</CustomerData>
')

我只是包含一些节点以便于阅读,你只需要粘贴剩下的节点。