How to get the no of occurrences of element in xml data in sql server - sql-server

In my xml i want to get the number of occurances of an element how can i do this.
for example in the below xml i want the number of times phone element is occuring
<Person>
<Name>abc</Name>
<Phone>1234</Phone>
<Phone>9876</Phone>
<Phone>5678</Phone>
</Person>
How can i achieve this ? Can someone help me .

declare #xml xml='<Person>
<Name>abc</Name>
<Phone>1234</Phone>
<Phone>9876</Phone>
<Phone>5678</Phone>
</Person>'
select #xml.value('count(//Person/Phone)','int')

You use XPATH. This site has a couple of examples of how to single out a specific type of node, by name. http://www.mycodeshare.com/item/1000000009/mssql-xml-query-using-xquery/
Start there and comment if it is not quite clear enough.

Related

Include text in ForXMLPath query in SQL Server

I want to include a line (simple text) in ForXMLPath query as
<Cat>
but I am having difficulties.
When I try it brings in weird characters with it.
Please help.
Thanks.
select
'<Cat>'
I expect this
<Cat>
but it displays below
<Cat>
I must admit, that your question is not clear...
XML is not just some text with fancy extras, but a very strictly organised text based container for data.
A simple SELECT '<Cat>' would never return as <Cat> without a FOR XML somewhere in your query. So please show us a (reduced!) example of your full query and the expected output, best provided as MCVE (a stand-alone sample with DDL, sample data, own attempt and expected output).
Just some general remarks:
If you want to place <Cat> within your XML the whole output will be broken XML. This opening tag demands for a closing </Cat> (or - alternatively - a self-closing <Cat />)
Assumably you try to add out-written tags to your XML as you'd do it in XSLT, JS, ASP.Net or any other XML/HTML producing approach.
Assumably your solution will be a FOR XML PATH() approach without the need of an out-written tag within your XML.
Just to give you an idea:
SELECT 'test' AS [SomeElement] FOR XML PATH('SomeRowTag'),ROOT('SomeRootTag');
prouces this XML
<SomeRootTag>
<SomeRowTag>
<SomeElement>test</SomeElement>
</SomeRowTag>
</SomeRootTag>
If you want to add a <Cat> element you could use an XPath like here
SELECT 'test' AS [Cat/SomeElement] --<-- You can add nest-levels here!
FOR XML PATH('SomeRowTag'),ROOT('SomeRootTag');
The result
<SomeRootTag>
<SomeRowTag>
<Cat>
<SomeElement>test</SomeElement>
</Cat>
</SomeRowTag>
</SomeRootTag>

SQL Server 2008 Xml Issue With Xml Escape Characters

Our current Point of Sale system executes too many queries in nested transactions that leave duplicated or partial data in place. I changed the entire thing to a single stored procedure where all sale item data is passed in as Xml, iterated through in a temp table, and saved to the database, then committed. However, SQL rejects special characters in the xml.
For example:
<?xml version="1.0" encoding="utf-16"?>
<list>
<item>
<objectid>bd99fcb6-3031-48b7-9a71-5f8cefe0a614</objectid>
<amount>50.00</amount>
<fee>1.50</fee>
<waivedfee>0.00</waivedfee>
<tax>0.00</tax>
<name>TEST & TEST PERSON</name>
<payeeid>197</payeeid>
<accountnumber>5398520352</accountnumber>
<checknumber />
<comedreceiptnumber />
<isexpedited>0</isexpedited>
<echeckrefnumber />
</item>
</list>
Fails. It tells me that there is an illegal character where & is located. I don't know why. It's escaped properly with &. I can't find any solutions online, anywhere. Everywhere people tell me to replace & with & - which is what I am doing!
Use XML PATH(''), it will encode the special characters for you.
SELECT 'TEST & TEST PERSON' FOR XML PATH('')
I figured it out. UTF-16 is correct. That Xml is fine. There was a final piece of xml, the ledgers, that were just plain strings with no encoding and no escaping special characters. Once I corrected that it all worked.
Thanks for the help!

SQL Server XML Value formatting newline

T-SQL XML value loses new line formats
I have XML file loaded into SQL server. I query this file to extract the nodes with value.
The problem is the new line characters are lost while selection. How to retain formatting so that when I display the text on the web, it not appear messy without line breaks.
See text and screenshots for details
T-SQL code:
declare #Text xml ;
set #Text= '<?xml version="1.0" encoding="utf-8"?>
<topic>
<L1>
<Subject>Subject text</Subject>
<Details>
Story Details are
This is paragraph
Text after After two line breaks
Text after After two line breaks
</Details>
</L1>
</topic>'
;with t as (select #Text [xmlcolumn])
--select * from t
SELECT x.a.value('(Subject)[1]','nvarchar(max)') as [Subject]
, x.a.value('(Details)[1]','nvarchar(max)') as [Details]
FROM t
cross apply
t.xmlcolumn.nodes('//L1') x(a)
Update: I misread your question - the problem with the newlines is purely in SQL Server Management Studio - it cannot represent those newlines. When you read your XML from an application in C# or VB.NET, those newlines will still be there - trust me.
But this original answer might also be relevant in other cases - you need to be aware that SQL Server is not storing your XML "as is" - it parses and converts it. So when you ask to get it back, it might look slightly different, but it's still the same XML functionally.
Yes, this is normal, expected behavior.
SQL Server stores your XML in a tokenized format - e.g. it doesn't store the actual, textual representation of your XML, but it parses and tokenizes your XML into XML fragments that are then stores inside this XML datatype.
Therefore, when you query it again, you'll get back a semantically correct and identical representation - but there's a possibility that certain textual representations are different.
E.g. when you pass in an empty XML element something like this:
<MyEmptyElement></MyEmptyElement>
you'll get back the "short" form of that when you retrieve the XML from SQL Server again:
<MyEmptyElement />
This is not the exact same text - but it's 100% the same XML from a semantic perspective.
As far as I know, you cannot influence this behavior in any way - you'll just have to live with it.

how to get the index of a point from geography?

How can i get the index of a point which is in my LineString?
I am using SQL Server 2008 R2.
I do have a geography type where a LineString is saved in.
I want now to get the index of two points on this LineString. So that I know which one occurs first.
Is this somehow possible?
Because right now i'm doing it for my self with a while loop... but it's really slow when i've got some more data in my database :/
EDIT: Ok, right now i'm trying to follow the solution from SQL to use CHARINDEX.
Some more background info:
I do have a geo point, I do have a linestring. I did get the intersecting points with a radius around my point from the linestring. Ok, now i want to try to get with the first intersecting point the index from this point on the LineString.
So i do have in my linestring some numbers like these patterns "1.123456 or 12.123456 or 123.123456" and my search point is also something like "1.123456 or 12.123456 or 123.123456"
The Problem is, that STIntersection gives me some different numbers back which are variable at the fractional digits. I thought about some string formatting, but i don't know how i should solve this. If there would be some nice regex features i think it would make my life easyier :)
I had a look through all of these functions but couldn't find anything for my needs.
Maybe some more experienced people could help me with that.
Thanks!
In case the datatype is varchar used. Please see below.
You can use CharIndex
DECLARE #document varchar(64)
SELECT #document = 'abcdef12345wuerzelchen'
SELECT CHARINDEX('abc', #document)
Once you have got the first occurrence point, Now you can check for another.
Declare #position int
Set #position = CHARINDEX('abc', #document)
SELECT CHARINDEX('wuerzelchen', #document, #position)
For more information you can check here

Read value of XML attribute in SQL Server 2005

I have one table contains field named source with varchar(max).
That field has following value
<OutPatientMedication
DateFormat="MM-dd-yyyy"
MedicationName="lisinopril 10 mg oral tablet"
Instructions="2 cap(s) orally once a day "
Status="Active"
Quantity="0"
Refills="0"
PrescriptionType="E">
</OutPatientMedication>
Now I want to fetch value of Instructions attribute.
How can I fetch value?
Prompt reply will be appreciated.
Thanks,
Dhruval Shah
Try something like this:
SELECT
CAST(Source AS XML).value('(/OutPatientMedication/#Instructions)[1]', 'varchar(200)')
FROM
dbo.YourTable
WHERE
(condition)
That should give you the desired value.
If you really have only XML in that column, I would strongly recommend making it of type XML in the database! Makes your life a lot easier, and save on disk space, too.

Resources