May 18, 2010 by Christoff Truter SQL XML
While playing around with the xml data type in SQL I noticed an interesting issue (maybe it will save someone some time), observe the following snippet:
DECLARE @cities AS XML SET @cities = '<cities> <city cityID="1" value="Berlyn" countryID="1" /> <city cityID="2" value="Hamburg" countryID="1" /> <city cityID="3" value="Frankfurt" countryID="1" /> <city cityID="4" value="Rotterdam" countryID="2" /> <city cityID="5" value="Amsterdam" countryID="2" /> </cities>' SELECT item.value('@cityID', 'INT') cityID, item.value('@value', 'VARCHAR(255)') value FROM @cities.nodes('//city[@countryID = 1]') t (item)
SELECT item.value('@cityID', 'INT') cityID, item.value('@value', 'VARCHAR(255)') value FROM @cities.nodes('//city') t (item) WHERE item.value('@countryID', 'INT') = @countryID
SELECT item.value('@cityID', 'INT') cityID, item.value('@value', 'VARCHAR(255)') value FROM @cities.nodes('//city[@countryID = ' + @countryID + ']') t (item)
DECLARE @countryID AS INT SET @countryID = 1 SELECT item.value('@cityID', 'INT') cityID, item.value('@value', 'VARCHAR(255)') value FROM @cities.nodes('//city[@countryID = sql:variable("@countryID")]') t (item)
Query XML data in a function with namespace September 5, 2014 by talaa123
I am facing problems while retrieving data from XML. with xmlnamespaces ('x-elements' as x) select tb.[Profile].value('(x:ppr/x:static/refId)[1]', 'varchar(22)') testCol from table1 tb The above code works perfectly fine. But, when I pass the XML path in a function it compiles correctly but doesn't return data upon calling but just the xml path (that is passed to it). CREATE FUNCTION testFunc ( @p varchar(22) ) RETURNS nvarchar(max) AS BEGIN DECLARE @Rs nvarchar(max); with xmlnamespaces ('x-elements' as x) select @Rs = tb.[Profile].value('(sql:variable("@p_path"))[1]', 'nvarchar(max)') from table1 tb RETURN (@Rs) END The result I am getting is "x:ppr/x:sta" (which is a path not the value) whereas it should return a value like "aJxk9pGntc5V" Please suggest a solution!