赞
踩
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语句将多列数据连接成一行
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.
单击超链接,您将在新窗口中获得结果。
You can note the following in this screenshot.
您可以在此屏幕截图中注意以下内容。
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.
在以下查询中,我们添加了以下参数。
- SELECT [CustomerID],
- [CustomerName],
- [CustomerCategoryName],
- [PrimaryContact],
- [AlternateContact],
- [PhoneNumber],
- [FaxNumber],
- [BuyingGroupName],
- [WebsiteURL],
- [DeliveryMethod]
- FROM [WideWorldImporters].[Website].[Customers]
- WHERE CustomerID < 3 FOR XML PATH('CustomerData'), ROOT('Customers');
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');
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输出中获得此列。
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.
它在输出中添加了以下内容。
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列,以及为各个列定义的别名。
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可能会变得很复杂,尤其是对于大型数据集。
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;
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.
您会注意到输出的差异。 它不只显示姓氏列的列名标签,因为它包含通配符。
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查询将获得以下输出。
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 ',' + AuthorName
- FROM @Authors
- WHERE 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 ',' + AuthorName
- FROM @Authors A1
- WHERE A1.ID = A2.ID FOR XML PATH('')
- ), 1, 1, '') AS Authors
- FROM @Authors A2;
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 子句
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。