I'm writing a user-defined function to extract values from an XML column in SQL Server which represents a simple dictionary of string key-value pairs. The only way I've made it work so far seems overly complex. Do you have any simplifying suggestions or tips for the DictValue
function below?
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]