FOR XML PATH('') 在连接行时如何工作

How FOR XML PATH('') works when concatenating rows

在 SQL 服务器中连接行时,FOR XML PATH ('') 子句如何工作?

我只想解释 FOR XML PATH ('') 子句的工作原理...

FOR XML PATH('xxx') 所做的是为结果集创建一个 XML 字符串,将每一行放在一个 <xxx></xxx> 元素中,并将行内的每一列值放在一个名称为对于那个专栏。

如果 PATH 为空(即 PATH('')),它会忽略 XML 代中的行元素。如果该列没有名称,它会忽略 XML 代中的列元素。当 PATH 均为空且列没有名称时,它实际上变成了所有行的字符串连接。

运行 以下陈述可以更好地了解过程:

-- Each row is in a <beta></beta> element
-- Each column in that row in a <alfa></alfa> element (the column name)
SELECT
    alfa=','+TABLE_SCHEMA + '.' + TABLE_NAME
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('beta');

-- Since the PATH is empty, the rows are not put inside an element
-- Each column in that row is in a <alfa></alfa> element (the column name)
SELECT
    alfa=','+TABLE_SCHEMA + '.' + TABLE_NAME
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('');

-- Since the PATH is empty, the rows are not put inside an element
-- Since the column has no name it is not put inside an element     
SELECT
    ','+TABLE_SCHEMA + '.' + TABLE_NAME
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('');

-- This uses the STUFF function to remove the leading comma to get a proper comma-seperated list    
SELECT STUFF((
    SELECT
        ','+TABLE_SCHEMA + '.' + TABLE_NAME
    FROM
        INFORMATION_SCHEMA.TABLES
    FOR
        XML PATH('')
    ),1,1,''
) AS comma_seperated_list;

现在我听到你在问:当我只是 select 来自 table 的列时,如何删除列名。有几种方法,按我的喜好顺序排列:

  • XQuery 属性:SELECT [text()]=column_name ...
  • 使用子查询 select 列值:SELECT (SELECT column_name) ...
  • CAST 列为其类型:SELECT CAST(column_value AS <TYPE of the column>) ...

示例:

SELECT
    [text()]=TABLE_NAME
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('');

SELECT
    (SELECT TABLE_NAME)
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('');

SELECT
    CAST(TABLE_NAME AS SYSNAME)
FROM
    INFORMATION_SCHEMA.TABLES
FOR
    XML PATH('');