【问题标题】:Call stored proc using xml output from a table使用表中的 xml 输出调用存储过程
【发布时间】:2011-11-21 17:47:18
【问题描述】:

在紧迫的期限内,我知道我最终可以解决这个问题,但我没有太多时间自己做。

我有一个表,其中包含许多其他列中的客户 ID 和帐号列。单个客户可能有多个帐户(许多行具有相同的客户 ID 但不同的帐号)。

对于表中的每个客户,我需要调用一个存储过程并将表中的数据以 xml 格式以以下格式传递。请注意,xml 适用于所有客户帐户。

<Accounts>
 <Account>
  <AccountNumber>12345</AccountNumber>
  <AccountStatus>Open</AccountStatus>
 </Account>
 <Account>
  <AccountNumber>54321</AccountNumber>
  <AccountStatus>Closed</AccountStatus>
 </Account>
</Accounts>  

所以我想我在两件事上需要帮助。首先,如何获取这种xml格式的数据。我假设我将使用 FOR XML 的一些变体。另一件事是我如何按客户 ID 分组,然后为每个客户 ID 调用一个存储过程?

【问题讨论】:

    标签: sql sql-server xml


    【解决方案1】:

    这样的事情会奏效。这是游标的少数情况之一。

    create table #a (CustomerID int, AccountNumber int, AccountStatus varchar(max))
    
    insert into #a values (1,12345,'Open')
    insert into #a values (1,54321,'Closed')
    insert into #a values (2,77777,'Open')
    insert into #a values (2,88888,'Closed')
    
    DECLARE @CustomerID int
    DECLARE @accounts xml
    
    DECLARE CurInvoice CURSOR READ_ONLY FAST_FORWARD FOR
        SELECT DISTINCT CustomerID 
        FROM #a  
    
    OPEN CurInvoice
    
    FETCH NEXT FROM CurInvoice INTO @CustomerID
    WHILE @@FETCH_STATUS = 0
        BEGIN
    
        set @accounts = (
        select AccountNumber,AccountStatus
        from #a
        where CustomerID = @CustomerID
        for xml path('Account'), root('Accounts'))
    
        exec MyProc @XmlInput = @accounts
    
    
    FETCH NEXT FROM CurInvoice INTO @CustomerID
    END
    CLOSE CurInvoice
    DEALLOCATE CurInvoice
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 2012-05-10
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 2012-04-18
      相关资源
      最近更新 更多