在 Microsoft 网站上wBob的帮助下,我现在有了一个干净的解决方案。当然,性能是一个问题,因为整个文档将被映射为单一路径,但改进留给读者作为建议的可能性:)
if object_id('VMConfigVal') is not null
drop function VMConfigVal
go
create function VMConfigVal(@x xml, @path varchar(max))
returns nvarchar(max)
as
begin
declare @ret nvarchar(max)
;with cte as
(
select value = x.c.value('.', 'varchar(50)')
, path = cast ( null as varchar(max) )
, node = x.c.query('.')
from @x.nodes('/*') x(c)
union all
select n.c.value('.', 'varchar(50)')
, isnull( c.path + '/', '/' )
+ n.c.value('local-name(.)', 'varchar(max)')
, n.c.query('*')
from cte c
cross apply c.node.nodes('*') n(c)
)
select @ret = value from cte where path = @path
return @ret
end
go
所以我现在可以做类似的事情:
select dbo.VMConfigVal(MyXMLConfig, '/hardware/devices/IDE/ChannelCount')
from someTable
甜的!