在连接行时,FOR XML PATH('')如何工作
FOR XML PATH ('')
子句在连接SQL Server中的行时如何工作?
我只想解释一下FOR XML PATH ('')
子句是如何工作的…
什么FOR XML PATH('xxx')
所做的是为结果集创build一个XMLstring,该string将每行放入一个<xxx></xxx>
元素中,并将每行的值放入行中的一个具有该列名称的元素中。
如果PATH为空,则省略XML生成中的行元素。 如果该列没有名称,则省略XML代中的列元素。 当两个PATH都是空的,并且列没有名字时,它实际上变成了所有行的string连接。
运行以下语句以更好地了解过程:
-- 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一列,如何删除列名? 有几种方法,按照我的喜好:
- XQuery属性:
SELECT [text()]=column_name ...
- 使用子查询来select列值:
SELECT (SELECT column_name) ...
- CAST列的types:
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('');