这是使用 XPath 谓词的另一种方法。
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, CustomColumns XML);
INSERT INTO @tbl (CustomColumns)
VALUES
(N'<CustomColumnsCollection>
<CustomColumn>
<Name>Brand</Name>
<DataType>0</DataType>
<Value>Duprim</Value>
</CustomColumn>
<CustomColumn>
<Name>LabelGroup</Name>
<DataType>0</DataType>
<Value/>
</CustomColumn>
</CustomColumnsCollection>');
-- DDL and sample data population, end
DECLARE @param VARCHAR(30) = 'Brand';
SELECT ID
, c.value('(Value/text())[1]', 'VARCHAR(50)') AS [Value]
FROM @tbl
CROSS APPLY CustomColumns.nodes('/CustomColumnsCollection/CustomColumn[(Name/text())[1] eq sql:variable("@param")]') AS t(c);
-- hard-coded value
SELECT ID
, c.value('(Value/text())[1]', 'VARCHAR(50)') AS [Value]
FROM @tbl
CROSS APPLY CustomColumns.nodes('/CustomColumnsCollection/CustomColumn[(Name/text())[1] eq "Brand"]') AS t(c);
输出
+----+--------+
| ID | Value |
+----+--------+
| 1 | Duprim |
+----+--------+
帮助您了解 MS Excel 使用的视图。如果您能提供一个最小的可重现示例,那就太好了:(1) DDL 和样本数据填充,即 CREATE 表加上 INSERT、T-SQL 语句。(2) 你需要做什么,即逻辑。(3) 基于上述#1 中的样本数据的期望输出。
用于 Excel 的 SQL
SELECT ID
, CustomColumns.value('(/CustomColumnsCollection/CustomColumn[(Name/text())[1] eq "Brand"]/Value/text())[1]', 'VARCHAR(50)') AS [Value]
FROM @tbl;