SQL FOR XML子句的各种用法

FOR XML子句有四种最基本的模式 
1、AUTO模式:返回数据表为起表名的元素,每一列的值返回为属性;
2、RAW模式:返回数据行为元素,每一列的值作为元素的属性; 
3、PATH模式:通过简单的XPath语法来允许用户自定义嵌套的XML结构、元素、属性值 
4、EXPLICIT模式:通过SELECT语法定义输出XML的结构
第1步:构造测试数据表及填充数据: 
--1.建表语句 
CREATE TABLE [dbo].[Users](
   [UserID] [int] IDENTITY(1,1) NOT NULL, 
   [FirstName] [nvarchar](50) NULL,
   [LastName] [nvarchar](50) NULL
         )  
--2.产生随机数SQL函数

CREATE FUNCTION [GenerateRandomItem] ( @LENGTH INT )
RETURNS NVARCHAR(255)
AS 
    BEGIN  
	--申明变量
        DECLARE @RandomNumber NVARCHAR(255)
        DECLARE @I SMALLINT
        DECLARE @RandNumber FLOAT
        DECLARE @Position TINYINT
        DECLARE @ExtractedCharacter VARCHAR(1)
        DECLARE @ValidCharacters VARCHAR(255)
        DECLARE @VCLength INT    
    --给变量赋值
        SET @ValidCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'    
        SET @VCLength = LEN(@ValidCharacters)
        SET @ExtractedCharacter = ''
        SET @RandNumber = 0
        SET @Position = 0
        SET @RandomNumber = '' 
        
        SET @I = 1 
        WHILE @I < ( @Length + 1 ) 
            BEGIN 
                SET @RandNumber = (SELECT RandNumber FROM [RandNumberView])
                SET @Position = CONVERT(TINYINT, ( ( @VCLength - 1 )* @RandNumber + 1 ))
                SELECT  @ExtractedCharacter = SUBSTRING(@ValidCharacters,@Position, 1)
                SET @I = @I + 1
                SET @RandomNumber = @RandomNumber + @ExtractedCharacter
            END
        RETURN @RandomNumber
    END
GO
CREATE VIEW [RandNumberView]
AS  
SELECT  RAND() AS [RandNumber]
--3.添加测试数据
INSERT INTO Users  
        (   
          FirstName ,  
          LastName   
        )  
SELECT  
dbo.GenerateRandomItem(10),  
dbo.GenerateRandomItem(10)     
GO 10
--4.测试查询

SQL FOR XML子句的各种用法

1.AUTO模式:

语句: SELECT UserID, FirstName,LastName FROM users FOR XML AUTO, XMLSCHEMA

说明:加上XMLSCHEMA,输出xml架构,不加则只输出数据。

输出:

SQL FOR XML子句的各种用法

2.RAW模式: 

语句:SELECT UserID, FirstName,LastName FROM users FOR XML RAW ('MyUsers')

说明:将元素命名为自定义的名称

输出:

SQL FOR XML子句的各种用法

3.PATH模式:

语句: SELECT UserID "@ID", FirstName "Name/FirstName",LastName "Name/LastName" FROM usersFOR XML PATH ('MyUsers')

说明:可以指定xml结构

输出:

SQL FOR XML子句的各种用法

4.EXPLICIT模式:(研究中,暂略... ... )



上一篇:Foundation HTML5 Canvas中的2处错误


下一篇:跨域CORS