SQL Server 2005: Recursive Hierarchies to XML
Suppose we have a recursive hierarchy stored in a relational database and we want to write it to XML. This might be for a variety of reasons – e.g. as a pre-cached input to a UI control, to export to another system using a pre-defined format, etc.
In SQL Server 2000, in order to get it straight to XML using FOR XML EXPLICIT, we would have to know the depth of the lowest node beforehand (without doing some very ugly dynamic SQL), so this does not help us.
It would be useful to access the data in the same order that it will appear in the XML. I.e.
Node1
Node2
Node3
Node4
Node5
Getting at the data in this order will allow us to iterate through the nodes in sequential order. This avoids using the DOM and is significantly quicker and more efficient as it avoids loading the whole structure into memory.
We could achieve this in SQL Server 2000 using a recursive table-valued UDF. In SQL Server 2005, we also have the option of using a recursive Common Table Expression (CTE) to achieve the same functional result. Let’s compare the two ways of doing it.
A CTE is a temporary named resultset referenced by a subsequent “outer query”. They can provide similar functionality to views and derived tables, but their real value is in recursive queries. Recursive CTE’s contain an “anchor member” and a “recursive member”, which are connected by a UNION ALL operator. They can be encapsulated by UDFs for reusability.
Data Preparation
Let’s create a table and insert hierarchical values.
CREATE TABLE Employees
(
empid int NOT NULL,
mgrid int NULL,
empname varchar(25) NOT NULL,
CONSTRAINT PK_Employees PRIMARY KEY(empid),
CONSTRAINT F
相关文档:
原网站无法访问,故保留google快照
How things work :
SQL
Select
Statement
Introduction
:
Ever asked your self how things work inside the
SQL
Select
statement? In this article we won’t be talking about how to writeSQL
Select
statem ......
Cross Apply使表可以和表值函数结果进行join, 这样表值函数的参数就可以使用一个结果集,而不是一个标量值,下面是book online的原文,有例子,有解释。
The APPLY operator allows you to invoke a table-valued function for each row returned by an outer table expression of a query. The table-valued function act ......
I'm continually trying to track down what service packs are installed on various SQL Servers I support. I can never find the right support page on Microsoft's site. So here's an article with all the SQL Server version information I can track down. If you know of any older versions or can help me fil ......
SQL Server 系统全局变量
@@CONNECTIONS
返回自上次启动以来连接或试图连接的次数。
@@CURSOR_ROWS
返回连接上最后打开的游标中当前存在的合格行的数量(返回被打开的游标中还未被读取的有效数据行的行数)
@@DATEFIRST
返回每周第一天的数字
@@ERROR
返回最后执行的SQL 语句的错误代码。
@@FETCH_STATUS
返 ......
-- FUN:存储过程分页
-- @Table nvarchar(255), -- 表名
-- @Fields nvarchar(1000) = ' * ', -- 需要返回的列
-- @OrderField nvarchar(255), -- 排序的字段名,一般为唯一标识
-- @OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
-- @PageSize int = 10, -- 每页有多少条记录
-- @PageIndex int = 1, -- 第 ......