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

前端 未结 2 1964
迷失自我
迷失自我 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:34

    I think your XML string is invalid. There's a letter "v" at the end of your start tag for STAFF:

    <STAFFv xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    

    To get the gender value you can select it like this:

    SELECT @XMLVALUECAST_.value('/*[1]/GENDER[1]','varchar(100)')

    0 讨论(0)
  • 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' ,
              '<?xml version="1.0" encoding="UTF-8"?>
                <STAFF xmlns:xsd="http://www.w3.org/2001/XMLSchema"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                     <EMPLOYEE_NUMBER>123456</EMPLOYEE_NUMBER>
                    <TITLE>Mr</TITLE>
                    <INITIALS>J</INITIALS>
                    <FORENAME>PEARL</FORENAME>
                    <SURNAME>HOFFMAN</SURNAME>
                    <GENDER>MALE</GENDER>
                    <DATE_OF_BIRTH>1992-01-01</DATE_OF_BIRTH>
                      <DEPARTMENT_DESC>SUPER SUPPORT TEAM</DEPARTMENT_DESC>
                      <JOB_TITLE_DESC>GENERAL DOGSBODY</JOB_TITLE_DESC>
                      <ORIGINAL_DATE_JOINED>2014-05-01</ORIGINAL_DATE_JOINED>
                      <CURRENT_EMPLOYEE financialyear="2014">Y</CURRENT_EMPLOYEE>
                      <INTERNAL_EMAIL xsi:nil="true" />
                      <CHANGE_TYPE>INSERT</CHANGE_TYPE>
                      <CHANGE_DATE>2014-03-27</CHANGE_DATE>
                </STAFF>'
            );
    
    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;
    
    0 讨论(0)
提交回复
热议问题