• ivor1994 - Monday, June 26, 2017 1:32 AM

    Thorn A Thank you for your time but i need to do it for over a 1000 fields in the column TemplateData and make from it another column so it's no sense to create a new table for each one.
    In my select i have error like this: 
    XML parsing: line 1, character 38, unable to switch the encoding
    There is any other solution for my problem ?
    I will be very grateful for any useful answers. 🙂

    Are you saying that you can't fix the xml? If so, this is a problem, If you're xml is malformed you can't query it with xQuery. This means you'd have to do something "silly" like use a giant string

    What is your actual goal here? Your original post said that you wanted to get the value of NumberSerializedLabels, however, now you say you need to get the value of 1,000 fields.

    You could change your query to do this instead, and then bring back your XML's values. This doesn't have a join but instead takes the first value of that data type. if you have any second/third entries of a node you'll need to change [1] to [2] or so on:
    SELECT X.XMLField.value('(Command/@Name)[1]','varchar(20)') AS CommandName,
       X.XMLField.value('(PrintSetup/NumberSerializedLabels)[1]','int') AS NumberSerializedLabels,
       X.XMLField.value('(PrintSetup/Printer)[1]','varchar(20)') AS Printer
    FROM #XML X
    GO

    Notice that returning the value for Name property for Command is different to the other fields.

    Again, this isn't going to work if your XML is malformed and or if it's not stored in an xml column (you can't xquery a (n)varchar). If it is still malformed, you need to fix it, both in your data, and whatever is producing it(so that you don't have this problem going forwards), and then store it as xml. If you can't fix it, you're going to in for a world of hurt and probably will need to attempt some kind of string manipulation query. That's going to be slow and tedious.

    A lot of users here will sing this song, but if you have data that represents a certain type of data, store it is that data. If you have number data, store it in a int or decimal column. If it's a date (only), then date. If you need the time as well then store in datetime/datetime2. Thus xml records go in an xml column, not a (n)varchar, as SQL Server has that data type. Using an XML column type would have flagged the malformed xml to you very early on, so you then wouldn't be attempting to fix it.

    Thom~

    Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
    Larnu.uk