Question

I need help with the following, as my knowledge of XML within SQL is non existent. Below is the table scripts to generate the table and data.

In the XML there is a XML Element with a name attribute of "RequiredField", i need to create a TSQL function to return the value contained in the value attribute. Please can anyone assist.

CREATE TABLE [MyTable]
( [UniqueID] INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
  [Description] VARCHAR(50) NOT NULL,
  [MetaData] XML NOT NULL )   
INSERT INTO [MyTable]
( [Description], [MetaData] )
SELECT  'My Description 1', '<properties xmlns="http://schemas.myschema.com/propertyInfo/additionalPropertyInfo.xsd"><item name="PropertyName" value="Property1" /><item name="RequiredField" value="true" /></properties>'
UNION
SELECT  'My Description 2', '<properties xmlns="http://schemas.myschema.com/propertyInfo/additionalPropertyInfo.xsd"><item name="PropertyName" value="Property2" /></properties>'

As you can see the second row doesnt contain that element, so it should return a null value. I seem to be running around in circles with the query, and havent really made much progress besides for the namespace part, but even that im not sure is right.

So something along the lines of this

CREATE FUNCTION GetRequiredFieldValue(@uniqueID INT)
    RETURNS BIT
AS
...
Was it helpful?

Solution

Try this:

create function GetRequiredFieldValue(@uniqueID INT) returns bit
as
begin
  declare @Ret bit;

  with xmlnamespaces(default 'http://schemas.myschema.com/propertyInfo/additionalPropertyInfo.xsd')
  select @Ret = MetaData.value('(/properties/item[@name = "RequiredField"])[1]/@value', 'bit')
  from MyTable
  where UniqueID = @UniqueID;

  return @Ret;
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top