这是我的示例 XML:
This is my sample XML:
<root>
<element>
<subelement>
<value code="code1">value1</value>
<value code="code2">value2</value>
</subelement>
</element>
</root>
这是我的测试查询:
DECLARE @tempTable TABLE (
ValueCode nvarchar(MAX),
Value nvarchar(MAX)
)
DECLARE @xml XML
select @xml = cast(c1 as xml) from OPENROWSET (BULK 'C:\test.xml', SINGLE_BLOB) as T1(c1)
INSERT INTO @tempTable
SELECT
Tbl.Col.value('subelement[1]/@code', 'NVARCHAR(MAX)'),
Tbl.Col.value('subelement[1]', 'NVARCHAR(MAX)')
FROM @xml.nodes('//element') Tbl(Col)
SELECT * FROM @tempTable
查询在执行时给出一行,其中 ValueCode 列包含 NULL,Value 列包含value1value2".我想得到的是用分隔符连接的属性和值.例如,我需要 ValueCode 来包含 'code1;code2' 和 Value 包含 'value 1;值2'.我怎样才能做到这一点?
The query, when executed, gives out a row with the ValueCode column containing NULL and the Value column containing 'value1value2'. What I would like to get would be the attributes and values concatenated with a separator. For example, I need ValueCode to contain 'code1; code2' and Value to contain 'value 1; value2'. How can I achieve that?
如果你想要连接字符串,你可以使用 xuery:
you can use xuery if you want concatenated strings:
SELECT
Tbl.Col.query('for $i in value return concat($i/text()[1], ";")').value('.', 'nvarchar(max)'),
Tbl.Col.query('for $i in value return concat($i/@code, ";")').value('.', 'nvarchar(max)')
FROM @xml.nodes('root/element/subelement') Tbl(Col);
如果您希望将值放入行中:
if you want your values into rows:
SELECT
Tbl.Col.value('.', 'nvarchar(max)'),
Tbl.Col.value('@code', 'nvarchar(max)')
FROM @xml.nodes('root/element/subelement/value') Tbl(Col);
sql 小提琴演示
这篇关于在 T-SQL 中通过 XQuery 选择时连接 xml 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
我可以在不编写 SQL 查询的情况下找出数据库列表Can I figure out a list of databases and the space used by SQL Server instances without writing SQL queries?(我可以在不编写 SQL 查询的情况下
如何创建对 SQL Server 实例的登录?How to create a login to a SQL Server instance?(如何创建对 SQL Server 实例的登录?)
如何通过注册表搜索知道SQL Server的版本和版本How to know the version and edition of SQL Server through registry search(如何通过注册表搜索知道SQL Server的版本和版本)
为什么会出现“数据类型转换错误"?使用 ExWhy do I get a quot;data type conversion errorquot; with ExecuteNonQuery()?(为什么会出现“数据类型转换错误?使用 ExecuteNonQuery()?)
如何将 DataGridView 中的图像显示到 PictureBox?How to show an image from a DataGridView to a PictureBox?(如何将 DataGridView 中的图像显示到 PictureBox?)
WinForms 应用程序设计——将文档从 SQL Server 移动WinForms application design - moving documents from SQL Server to file storage(WinForms 应用程序设计——将文档从 SQL Server 移动到文件存