Iterate through XML variable in SQL Server

前端 未结 2 2004
北海茫月
北海茫月 2021-01-07 04:18

I have a XML variable in a stored procedure (SQL Server 2008), its sample value is


   Low
   

        
2条回答
  •  花落未央
    2021-01-07 04:36

    Something like this?

    DECLARE @XmlVariable XML = '
                                  Low
                                  Medium
                                  High
                                '
    
    INSERT INTO dbo.YourTargetTable(CategoryColumn)
      SELECT 
         XTbl.Cats.value('.', 'varchar(50)')
      FROM 
         @XmlVariable.nodes('/parent_node/category') AS XTbl(Cats)
    

    Update: if you must use the old legacy stored procedure and cannot change it (that would be my preferred way of doing this), then you would have to do the row-by-agonizing-row (RBAR) looping yourself, e.g. by using a table variable:

    -- declare temporary work table
    DECLARE @RbarTable TABLE (CategoryName VARCHAR(50))
    
    -- insert values into temporary work table
    INSERT INTO @RbarTable(CategoryName)
      SELECT 
         XTbl.Cats.value('.', 'varchar(50)')
      FROM 
         @XmlVariable.nodes('/parent_node/category') AS XTbl(Cats)
    
    -- declare a single category
    DECLARE @CategoryNameToBeInserted VARCHAR(50)
    
    -- get the first category
    SELECT TOP 1 @CategoryNameToBeInserted = CategoryName FROM @RbarTable
    
    -- as long as we have data
    WHILE @CategoryNameToBeInserted IS NOT NULL
    BEGIN
        -- execute your stored procedure here.....    
        EXEC sp_executesql N'dbo.YourStoredProcedure @CategoryName', 
                           N'@CategoryName VARCHAR(50)', 
                           @CategoryName = @CategoryNameToBeInserted
    
        -- delete the category we just inserted from the temporary work table
        DELETE FROM @RbarTable WHERE CategoryName = @CategoryNameToBeInserted
    
        -- see if we still have more categories to insert    
        SET @CategoryNameToBeInserted = NULL
        SELECT TOP 1 @CategoryNameToBeInserted = CategoryName FROM @RbarTable ORDER BY CategoryName
    END
    

提交回复
热议问题