我正在编写一个用户定义的函数来从 SQL Server 中的 XML 列中提取值,该列表示字符串键值对的简单字典。到目前为止,我使它工作的唯一方法似乎过于复杂。您对以下DictValue
功能有任何简化的建议或技巧吗?
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DictValue]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[DictValue]
go
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableWithXmlColumn]') AND type in (N'U'))
DROP TABLE [dbo].[TableWithXmlColumn]
go
create table TableWithXmlColumn (
Id int identity primary key
,Dict xml
)
go
create function DictValue(
@id int
,@key nvarchar(max)
) returns nvarchar(max) as begin
declare @d xml -- string Dictionary
select @d = Dict from TableWithXmlColumn where Id = @id
declare @value xml
select
@value = d.Pair.value('data(.)', 'nvarchar(max)')
from
@d.nodes('/StringDictionary/Pair') as d(Pair)
where
@key = d.Pair.value('./@Key', 'nvarchar(max)')
return convert(nvarchar(max), @value)
end
go
declare @xmlId int
insert TableWithXmlColumn (Dict) values (
N'<?xml version="1.0" encoding="utf-16"?>
<StringDictionary>
<Pair Key="color">red</Pair>
<Pair Key="count">123</Pair>
</StringDictionary>')
set @xmlId = scope_identity()
select
dbo.DictValue(@xmlId, 'color') as color
,dbo.DictValue(@xmlId, 'count') as [count]