sql limit 子句

As SQL professionals, we often have to deal with XML data in our databases. This article will help you walk through several examples of using ‘FOR XML PATH’ clause in SQL Server.

作为SQL专业人员,我们经常不得不处理数据库中的XML数据。 本文将帮助您逐步了解在SQL Server中使用“ FOR XML PATH”子句的几个示例。

We get the requirement to display the data from the relational SQL table in various formats. Sometimes developers want to retrieve data in the XML format from the SQL tables holding relational data in regular data types. SQL Server supports XML data using the FOR XML clause. We can easily convert existing data into the XML format using this. We have the following modes available in the FOR XML clause. We can use the FOR XML clause to join or concatenate multiple columns into a single row output as well.

我们要求以各种格式显示关系SQL表中的数据。 有时,开发人员希望从SQL表中以常规数据类型保存关系数据的XML格式的数据。 SQL Server使用FOR XML子句支持XML数据。 我们可以轻松地将现有数据转换为XML格式。 在FOR XML子句中,可以使用以下模式。 我们也可以使用FOR XML子句将多列联接或连接到单行输出中。

We use the FOR XML PATH SQL Statement to concatenate multiple column data into a single row

我们使用FOR XML PATH SQL语句将多列数据连接成一行

  • RAW
    生的
  • Auto
    汽车
  • EXPLICIT
    显式
  • PATH
    路径

示例1:FOR XML PATH子句的基本用法 (Example 1: Basic use of the FOR XML PATH clause)

Let’s use the WideWorldImporters sample database for this part of the article. Execute the following query, and it retrieves the data in a grid format.

让我们在本文的这一部分中使用WideWorldImporters示例数据库。 执行以下查询,并以网格格式检索数据。

SELECT [CustomerID], [CustomerName], [CustomerCategoryName], [PrimaryContact], [AlternateContact], [PhoneNumber], [FaxNumber], [BuyingGroupName], [WebsiteURL], [DeliveryMethod]
FROM [WideWorldImporters].[Website].[Customers]
WHERE CustomerID < 3;

Click on the Result to Text in the SSMS toolbar and rerun the query.

单击SSMS工具栏中的“结果文本”,然后重新运行查询。

It gives the same result in a text format. In the following screenshot, we do not see the complete results because you have to scroll the bar in SSMS to see other columns.

它以文本格式给出相同的结果。 在下面的屏幕截图中,我们看不到完整的结果,因为您必须在SSMS中滚动条以查看其他列。

Let’s use the FOR XML PATH clause in previous query and get results in a grid format.

让我们在上一个查询中使用FOR XML PATH子句,并以网格格式获取结果。

To use Grid format, you can click on Results to Grid in the SSMS menu bar as shown below.

要使用网格格式,可以在SSMS菜单栏中单击“结果网格化”,如下所示。

SELECT [CustomerID], [CustomerName], [CustomerCategoryName], [PrimaryContact], [AlternateContact], [PhoneNumber], [FaxNumber], [BuyingGroupName], [WebsiteURL], [DeliveryMethod]
FROM [WideWorldImporters].[Website].[Customers]
WHERE CustomerID < 3 FOR XML PATH;

We get the XML output as a hyperlink.

我们将XML输出作为超链接获取。

Click on the hyperlink and you get the results in a new window.

单击超链接,您将在新窗口中获得结果。

XML output

You can note the following in this screenshot.

您可以在此屏幕截图中注意以下内容。

  • Each row is embedded into <row> and </row> clause
    每行都嵌入到<row>和</ row>子句中
  • In each row, each column value is embedded into <ColumnName> and </ColumnName> clauses
    在每一行中,每个列值都嵌入到<ColumnName>和</ ColumnName>子句中

示例2:将元素指令与FOR XML PATH一起使用 (Example 2: Use of an Elements directives with FOR XML PATH)

We can use ELEMENTS directives to replace <row> clauses with each row. Previously, we did not specify the ELEMENTS directive, so it returns the default value.

我们可以使用ELEMENTS指令将<row>子句替换为每一行。 以前,我们没有指定ELEMENTS指令,因此它返回默认值。

Suppose we want to define root element as Customers. Each row data should be embedded between <CustomerData> and </CustomerData tag>.

假设我们要将根元素定义为“客户”。 每行数据应嵌入在<CustomerData>和</ CustomerData标签>之间。

In the following query, we added the parameters as following.

在以下查询中,我们添加了以下参数。

  • FOR XML PATH(‘CustomerData’) for each row data
  • 每行数据的FOR XML PATH('CustomerData')
  • ROOT(‘Customers’) for the root tag
  • 根标签的ROOT('Customers')
SELECT [CustomerID], [CustomerName], [CustomerCategoryName], [PrimaryContact], [AlternateContact], [PhoneNumber], [FaxNumber], [BuyingGroupName], [WebsiteURL], [DeliveryMethod]
FROM [WideWorldImporters].[Website].[Customers]
WHERE CustomerID < 3 FOR XML PATH('CustomerData'), ROOT('Customers');

示例3:XML输出中的列别名 (Example 3: Column Alias in the XML output)

Let’s say we want to use CustomerID attribute instead of the <Customerdata> meta data tag. To do so, we can add an alias in the Select statement and use an alias with the @ parameter.

假设我们要使用CustomerID属性而不是<Customerdata>元数据标记。 为此,我们可以在Select语句中添加别名,并在@参数中使用别名。

In the following query, We use @CustomerID in the select statement to show the CustomerID as well in the row tag.

在以下查询中,我们在select语句中使用@CustomerID在行标记中也显示CustomerID。

SELECT [CustomerID] as "@CustomerID", [CustomerName], [CustomerCategoryName], [PrimaryContact], [AlternateContact], [PhoneNumber], [FaxNumber], [BuyingGroupName], [WebsiteURL], [DeliveryMethod]
FROM [WideWorldImporters].[Website].[Customers]
WHERE CustomerID < 3 FOR XML PATH('Customer'), ROOT('Customers');

示例4:NULL值和XML输出 (Example 4: NULL values and the XML output)

Let’s further customized the output using the FOR XML CLAUSE. In the further output, we will use the following data set.

让我们使用FOR XML CLAUSE进一步自定义输出。 在进一步的输出中,我们将使用以下数据集。

You can get this data using the following query in the AdventureWorks database.

您可以使用AdventureWorks数据库中的以下查询获取此数据。

SELECT TOP 5 [PersonType], [FirstName], [MiddleName], [LastName]FROM [AdventureWorks2017].[Person].[Person];

Let’s view this data in the XML format with the FOR XML PATH clause and alias in the FirstName column.

让我们以XML格式查看此数据,并在FirstName列中使用FOR XML PATH子句和别名。

SELECT TOP 5 [FirstName] AS '@FirstName', [MiddleName], [LastName]
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee');

In this output, You can notice that Kim does not have a middle name therefore, you do not get this column in the XML output.

在此输出中,您会注意到Kim没有中间名,因此您不会在XML输出中获得此列。

XML view of the selected data

We can use the ELEMENTS XSINIL parameter to display NULL values as well in the XML output.

我们可以使用ELEMENTS XSINIL参数在XML输出中也显示NULL值。

SELECT TOP 5 [FirstName] AS '@FirstName', [MiddleName], [LastName]
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;

It adds the following things in the output.

它在输出中添加了以下内容。

  • xsi:nil=”true” for the NULL values
  • xsi:nil =“ true”表示NULL值
  • It also add XML definition in the root element
    <Employee xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  • 它还在根元素中添加XML定义
    <Employee xmlns:xsi =” http://www.w3.org/2001/XMLSchema-instance”

示例5:除单独的行标签之外的其他列的列别名 (Example 5: Column Alias on columns other than the individual row tag)

Suppose we want to add an alias to columns other than the alias for the individual row tag. In the following query, we defined alias on the middle name and the last name column.

假设我们要为各个行标签的别名以外的其他列添加别名。 在以下查询中,我们在中间名和姓氏列上定义了别名。

SELECT TOP 5 [FirstName] AS '@FirstName', [MiddleName] as 'Person/MiddleName', [LastName] as 'Person/LastName'
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL; ;

In the following screenshot, we get both the MiddleName and LastName column are enclosed in the <person> tag along with the alias we defined for individual columns.

在下面的屏幕截图中,我们在<person>标记中同时包含了MiddleName和LastName列,以及为各个列定义的别名。

Column alias and new column

Let’s add a new column in the SELECT statement. We need to be careful in the order of the select statement.

让我们在SELECT语句中添加一个新列。 我们需要注意select语句的顺序。

The correct order is to use the new column after the alias columns.

正确的顺序是在别名列之后使用新列。

SELECT TOP 5 [FirstName] AS '@FirstName', [MiddleName] AS 'Person/MiddleName', [LastName] AS 'Person/LastName', EmailPromotion
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;

If we use this new column in between the alias columns, you still get the output, but it might complicate the XML as shown in the following screenshots.

如果我们在别名列之间使用这个新列,您仍然会得到输出,但是它可能会使XML复杂化,如以下屏幕截图所示。

SELECT TOP 5 [FirstName] AS '@FirstName', [MiddleName] AS 'Person/MiddleName', EmailPromotion, [LastName] AS 'Person/LastName'
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;

In this screenshot, we get different <person> meta tag for each column with the alias. It might make it complicated to interpret the XML, especially for large data sets.

在此屏幕截图中,我们为每个具有别名的列获取了不同的<person>元标记。 解释XML可能会变得很复杂,尤其是对于大型数据集。

示例6:通配符的使用 (Example 6: Use of the Wildcard character )

We can use the wildcard character * with the FOR XML PATH as well. Once we specify a wildcard with a specific column, in the output, we get that column without the column name.

我们也可以将通配符*与FOR XML PATH一起使用。 一旦指定了具有特定列的通配符,则在输出中,我们将获得该列而没有列名。

In the following query, we specified the wildcard character for all columns. In the output, we can see it does not return the column name in the XML.

在以下查询中,我们为所有列指定了通配符。 在输出中,我们可以看到它没有返回XML中的列名。

SELECT TOP 5 [FirstName] "*", [MiddleName] "*", [LastName] "*"
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;
Wildcard character in XML

Let’s remove the wildcard character for the FirstName column.

让我们删除FirstName列的通配符。

SELECT TOP 5 [FirstName], [MiddleName] "*", [LastName] "*"
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;

In the output, you get the column name tag for the Firstname because it does not contain the wildcard character. For other columns, it does not give the column name tag.

在输出中,您将获得FirstName的列名标签,因为它不包含通配符。 对于其他列,它不提供列名标签。

Similarly, in the below query, we use wildcard characters only for the Lastname column.

同样,在下面的查询中,我们仅对“姓氏”列使用通配符。

SELECT TOP 5 [FirstName], [MiddleName], [LastName] "*"
FROM [AdventureWorks2017].[Person].[Person] FOR XML PATH('Person'), ROOT('Employee'), ELEMENTS XSINIL;

You can notice the difference in the output. It does not show column name tags only for the LastName column because it contains the wildcard character.

您会注意到输出的差异。 它不只显示姓氏列的列名标签,因为它包含通配符。

示例7:对XML输出使用XMLNAMESPACE (Example 7: Use of a XMLNAMESPACE for the XML output)

We can use XMLNAMESPACE with the FOR XML PATH to declare a namespace and use it in the Select statements. In the following example, we specified XMLNAMESPACE. We call it in the select query.

我们可以将XMLNAMESPACE与FOR XML PATH一起使用来声明一个名称空间,并在Select语句中使用它。 在下面的示例中,我们指定了XMLNAMESPACE。 我们在选择查询中将其称为。

WITH XMLNAMESPACES('SQLShack' as URL)
SELECT 'https://www.sqlshack.com/' as 'URL'
FOR XML PATH

You get the following output with XMLNAMESPACE query.

使用XMLNAMESPACE查询将获得以下输出。

示例8:使用FOR XML PATH子句创建一个逗号分隔的字符串 (Example 8: Create a comma-separated string using the FOR XML PATH clause)

We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let’s create an Authors table and insert a few records into it.

我们可以使用FOR XML PATH从现有数据中准备一个逗号分隔的字符串。 让我们创建一个Authors表并将一些记录插入其中。

declare @Authors Table(ID int,AuthorName varchar(20))
Insert @Authors(ID,AuthorName)
Values
(1,'Rajendra'),(1,'Raj')
,(2,'Sonu'),(2,'Raju')
,(3,'Akshita'),(3,'Akshu')
,(4,'Kashish'),(4,'Kusum')
select * from @Authors

In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.

在数据中,我们可以看到有一个ID列和AuthorName列。 如果我们只选择记录,它将以以下格式给出输出。

Assume, we need to combine the data based on the ID column and display list of authors in a comma-separated view.

假设,我们需要根据ID列合并数据,并以逗号分隔的视图显示作者列表。

We can use FOR XML PAH and get the output using the following query.

我们可以使用FOR XML PAH并使用以下查询获取输出。

SELECT DISTINCT ID,
(SELECT SUBSTRING((SELECT ',' + AuthorNameFROM @AuthorsWHERE ID = t.ID FOR XML PATH('')), 2, 200000)
) AS AuthorName
FROM @Authors t;

Alternatively, we can use the STUFF function in SQL Server along with the FOR XML PATH to retrieve the same result.

或者,我们可以使用SQL Server中的STUFF函数以及FOR XML PATH来检索相同的结果。

We use the STUFF function to replace a part of a string with substring at a specified position. The STUFF function makes it easy to write the above query and get the same result set.

我们使用STUFF函数在指定位置用子字符串替换字符串的一部分。 STUFF函数使编写上面的查询并获得相同的结果集变得容易。

SELECT DISTINCT ID, STUFF(
(SELECT ',' + AuthorNameFROM @Authors A1WHERE A1.ID = A2.ID FOR XML PATH('')
), 1, 1, '') AS Authors
FROM @Authors A2;

结论 (Conclusion)

In this article, we demonstrated FOR XML PATH clause and its usage with different examples. We further learned to customize the XML output. If you have any comments or questions, feel free to leave them in the comments below.

在本文中,我们通过不同的示例演示了FOR XML PATH子句及其用法。 我们进一步学习了定制XML输出的方法。 如果您有任何意见或疑问,请随时将其留在下面的评论中。

翻译自: https://www.sqlshack.com/for-xml-path-clause-in-sql-server/

sql limit 子句

sql limit 子句_SQL Server中的FOR XML PATH子句相关推荐

  1. sql数据透视_SQL Server中的数据科学:取消数据透视

    sql数据透视 In this article, in the series, we'll discuss understanding and preparing data by using SQL ...

  2. sql语句截断_SQL Server中SQL截断和SQL删除语句之间的区别

    sql语句截断 We get the requirement to remove the data from the relational SQL table. We can use both SQL ...

  3. sql 实现决策树_SQL Server中的Microsoft决策树

    sql 实现决策树 Decision trees, one of the very popular data mining algorithm which is the next topic in o ...

  4. sql判断基数_SQL Server中的基数估计框架版本控制

    sql判断基数 This is a small post about how you may control the cardinality estimator version and determi ...

  5. oracle 动态sql列转行_SQL Server中动态列转行

    http://www.cnblogs.com/gaizai/p/3753296.html 一.本文所涉及的内容(Contents) 三.实现代码(SQL Codes) (一) 首先我们先创建一个测试表 ...

  6. 对于数据给定范围sql取数_SQL Server中的报表–根据给定日期范围内提取的数据创建图表

    对于数据给定范围sql取数 介绍 ( Introduction ) I recently heard from a lady from overseas who wanted to find a qu ...

  7. server sql 本月最后一天_SQL SERVER中求上月、本月和下月的第一天和最后一天 DATEADD DATEDIFF...

    1.上月的第一天 SELECT CONVERT(CHAR(10),DATEADD(month,-1,DATEADD(dd,-DAY(GETDATE())+1,GETDATE())),111) 2.上月 ...

  8. 第3周 区_SQL Server中管理空间的基本单位

    第3周 区_SQL Server中管理空间的基本单位 原文:第3周 区_SQL Server中管理空间的基本单位 哇哦,SQL Server性能调优培训已经进入第3周了!同时你已经对SQL Serve ...

  9. 灵活运用 SQL Server 数据库的 FOR XML PATH

    起因¶ 今天欧阳冰提出一个报表需求,其核心部分可以简化为这样一张表格: 调度单号 与调度单相关的多张作业单号 001 0001/0002/0003 002 0004 003 0005/0006/000 ...

最新文章

  1. Linux之 xstart调用 x11vnc远程图形化桌面
  2. 20190403vim编辑器week1_day3
  3. java学习(92):线程的创建方法一
  4. 某释放驱动的样本分析及手杀报告
  5. java-Servlet编码/异常处理
  6. Office 2013集成SP1
  7. ESXi7.0 安装 MacOS (ESXi Unlocker 3.0.3)
  8. ArcMap 计算面积对应平面坐标系,投影坐标系 2000坐标系 84坐标系
  9. vue针对ele的form组件校验
  10. 电脑时间校准方法,怎么校准电脑时间
  11. 解决 “Windows 功能” 没有Hyper-V
  12. 【手绘漫画】面试必考之图解逆转单链表/单链表逆序
  13. 六星经典CSAPP笔记(2)信息的操作和表示
  14. 笔试题——硬币与金币(概率)
  15. 电磁场与仿真软件(30)
  16. c语言程序设计实践万年历,c语言程序设计万年历-20210408030342.docx-原创力文档
  17. 想开服,又没有技术怎么办?传奇开服技术要学多久?开服技术好学吗
  18. 使用R语言绘制graph:无向图(ug)和有向无环图(dag)
  19. java1.17知识点回顾
  20. 计算机单片机考试作弊检讨书,关于大学生考试作弊检讨书1000字范文[共7页]

热门文章

  1. 触摸传感器的电路图符号_如何看懂汽车电路常用图形符号,看完这篇文章就懂了...
  2. rms 公式 有效值_有效值是电流电压的均方根值吗?
  3. [转帖]安华高收购博通
  4. 《SQL Server 2008从入门到精通》--20180703
  5. window.event对象详尽解析
  6. 关于$.ajax的请求格式
  7. usaco2.11Ordered Fractions
  8. oracle 942错误(exp imp 出问题的解决方案)
  9. JavaScript学习(八十五)—数据类型的转换
  10. winxp系统的驱动可用于win2k吗?_收藏!工业机器人伺服系统常见问题汇总