TSQL XML FUNCTION

醉酒当歌 提交于 2019-12-11 05:07:13

问题


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
...

回答1:


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


来源:https://stackoverflow.com/questions/14230590/tsql-xml-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!