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.测试查询
1.AUTO模式:
语句: SELECT UserID, FirstName,LastName FROM users FOR XML AUTO, XMLSCHEMA
说明:加上XMLSCHEMA,输出xml架构,不加则只输出数据。
输出:
2.RAW模式:
语句:SELECT UserID, FirstName,LastName FROM users FOR XML RAW ('MyUsers')
说明:将元素命名为自定义的名称
输出:
3.PATH模式:
语句: SELECT UserID "@ID", FirstName "Name/FirstName",LastName "Name/LastName" FROM usersFOR XML PATH ('MyUsers')
说明:可以指定xml结构
输出:
4.EXPLICIT模式:(研究中,暂略... ... )