FOR XML PATH('')在连接行时的工作原理

时间:2016-02-02 08:34:38

标签: sql-server tsql for-xml-path

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

我只想解释FOR XML PATH ('')子句如何工作......

1 个答案:

答案 0 :(得分:14)

FOR XML PATH('xxx')所做的是为结果集创建一个XML字符串,该字符串将每一行放在<xxx></xxx>元素中,每个列值放在该行中,该元素具有该列的名称。

如果PATH为空(即PATH('')),则省略XML生成中的row元素。如果列没有名称,则省略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;

现在我听到你问:当我只是从表中选择一列时,如何删除列名。根据我的偏好,有几种方法:

  • XQuery属性:SELECT [text()]=column_name ...
  • 使用子查询选择列值:SELECT (SELECT column_name) ...
  • 将列标注为其类型: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('');