1

我需要以下方面的帮助,因为我不了解 SQL 中的 XML。下面是生成表格和数据的表格脚本。

在 XML 中有一个名称属性为“RequiredField”的 XML 元素,我需要创建一个 TSQL 函数来返回 value 属性中包含的值。请任何人都可以提供帮助。

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

如您所见,第二行不包含该元素,因此它应该返回一个空值。我似乎在查询中绕着圈子跑来跑去,除了命名空间部分之外并没有真正取得太大进展,但即使是我也不确定是否正确。

所以类似这样的东西

CREATE FUNCTION GetRequiredFieldValue(@uniqueID INT)
    RETURNS BIT
AS
...
4

1 回答 1

2

试试这个:

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
于 2013-01-09T08:15:15.180 回答