CONVERTING SQL NVARCHAR(MAX) TO XML and getting a Value from XML string

前端 未结 2 1963
迷失自我
迷失自我 2021-01-03 10:07

I am trying read from the nodes of a column -where an XML string is stored. The column is of type NVARCHAR(MAX).

The following is the script to create table - S

2条回答
  •  清酒与你
    2021-01-03 10:39

    First of all why don't you save the column in XML? Another thing that you have error in the tag. I believe that it is supposed to be STAFF, not STAFFv. And the last thing is that UTF-8 is used instead of the UTF-16 for XML encoding. So the final code is:

    CREATE TABLE #XML_Dummy
        (
          [ID] [INT] IDENTITY(1, 1)
                     NOT NULL ,
          [Name] [NVARCHAR](50) NULL ,
          [XMLValue] [NVARCHAR](MAX) NULL
        ); 
    
    INSERT  INTO #XML_Dummy
            ( [Name] ,
              [XMLValue]
            )
    VALUES
            ( 'abcd' ,
              '
                
                     123456
                    Mr
                    J
                    PEARL
                    HOFFMAN
                    MALE
                    1992-01-01
                      SUPER SUPPORT TEAM
                      GENERAL DOGSBODY
                      2014-05-01
                      Y
                      
                      INSERT
                      2014-03-27
                '
            );
    
    SELECT
        b.x.value('/STAFF[1]/GENDER[1]', 'varchar(100)')
    FROM
        #XML_Dummy a
        CROSS APPLY (
                      SELECT
                       CAST(CAST ([XMLValue] AS VARCHAR(MAX)) AS XML) x
                    ) b;
    DROP TABLE #XML_Dummy;
    

提交回复
热议问题