php 字符串串联

Previously I have introduced string concatenation by demonstrating how not to use Transact-SQL to concatenate strings. In this part I will focus on XML composition, and will demonstrate how to correctly implement it in order to concatenate strings.

以前,我通过演示如何使用Transact-SQL来串联字符串来介绍字符串串联。 在这一部分中,我将重点介绍XML组合 ,并将演示如何正确实现它以连接字符串。

I assume that you already understand what XML is, and how it is implemented in SQL Server. You might not know this, but I have written extensively on this very subject in my “regular” blog, at http://milambda.blogspot.com (there is plenty to choose from, once you locate it: http://milambda.blogspot.com/search?q=xml). In the very unlikely case that you might not be a fan of XML, stay tuned – part three of this article is XML-free.

我假设您已经了解什么是XML,以及如何在SQL Server中实现它。 您可能不知道这一点,但是我已经在我的“常规”博客中http://milambda.blogspot.com上广泛地撰写了有关此主题的文章(找到后可以选择很多: http:// milambda .blogspot.com / search?q = xml )。 如果您不太可能不喜欢XML,请继续关注–本文的第三部分不包含XML。

In order to properly utilize XML it needs to be treated as what it is – a complex data type. Once an XML document (or fragment) is composed, the only reliable way of transforming it is to use the built-in XML retrieval methods. So, in order to correct the query I used at the end of part one of this article, I will use the QUERY and the VALUE XML retrieval methods.

为了正确利用XML,需要将其视为一种复杂的数据类型。 组成XML文档(或片段)后,对其进行转换的唯一可靠方法是使用内置的XML检索方法。 因此,为了更正我在本文第一部分结尾处使用的查询,我将使用QUERY和VALUE XML 检索方法。


select titles.title_id,titles.title,titles.price,authors= stuff((select '; ' + authors.au_lname + ', ' + authors.au_fnamefrom dbo.titleauthorinner join dbo.authorson authors.au_id = titleauthor.au_idwhere (titleauthor.title_id = titles.title_id)order by titleauthor.au_ordfor xml path('author'), root('authors'), type).query('authors/author').value('.', 'varchar(64)'), 1, 2, '')from dbo.titleswhere (titles.title_id = 'TC7777')Result:title_id title           price authors
-------- --------------- ----- ---------------------------------------------------
TC7777   Sushi, Anyone?  14,99 Yokomoto, Akiko; O'Leary, Michael; Gringlesby, Burt(1 row(s) affected)

Figure 1: XML composition with XML retrieval methods.

图1:具有XML检索方法的XML组合。

The query in Figure 1 retrieves three attributes of a particular book from the dbo.books table and uses a correlated subquery with the FOR XML directive to retrieve the related data about authors from the dbo.authors and dbo.titleauthor tables, which is then concatenated into a single string in the authors column of the outer query. The FOR XML subquery uses the TYPE setting, which instructs the database engine to return an XML document. The QUERY XML retrieval method is then used to extract the concatenated string from the XML document, and finally the VALUE method is used to return the data as a VARCHAR(64) value.

图1中的查询从dbo.books表中检索特定书的三个属性,并使用带有FOR XML指令的相关子查询从dbo.authors和dbo.titleauthor表中检索有关作者的相关数据,然后将它们连接在一起放入外部查询的authors列中的单个字符串中。 FOR XML子查询使用TYPE设置,该设置指示数据库引擎返回XML文档。 然后使用QUERY XML检索方法从XML文档中提取连接的字符串,最后使用VALUE方法将数据作为VARCHAR(64)值返回。

The FOR XML directive can be used to create a concatenated string from data of any type, as long as it can be represented as a string. By using the BASE64 setting of the FOR XML directive you can even represent binary values as strings with a standard, and reversible, conversion technique.

只要可以将XML指令表示为字符串,就可以使用FOR XML指令从任何类型的数据创建串联的字符串。 通过使用FOR XML指令的BASE64设置,您甚至可以使用标准的可逆转换技术将二进制值表示为字符串。

Depending on the way the results of this query are going to be used, you might need some way of distinguishing between the values being concatenated and the values used to delimit them (for instance, to be able to create a normalised representation of the data at the destination). In the example above I’ve used the semi-colon to delimit the co-authors’ names, making it possible to distinguish between individual full names.

根据查询结果的使用方式,您可能需要某种方式来区分正在连接的值和用于定界它们的值(例如,为了能够在以下位置创建数据的规范化表示形式目的地)。 在上面的示例中,我使用分号分隔了共同作者的姓名,从而可以区分各个全名。

The SQL Server implementation of XML composition not only guarantees that the concatenated result will contain all of the corresponding values and in the correct shape, it also guarantees that they will be placed in the XML document in the specified order. In case the concatenated values need to be sorted, with XML composition you have complete control over the ordering: simply use the ORDER BY clause in the FOR XML query, which is also demonstrated in Figure 1.

SQL Server XML组合的实现不仅保证连接的结果将包含所有相应的值并且具有正确的形状 ,还保证将它们以指定的顺序放置在XML文档中。 如果需要对连接的值进行排序,则可以使用XML组成对顺序进行完全控制:只需在FOR XML查询中使用ORDER BY子句即可,如图1所示。

The FOR XML subquery technique is completely integrated with the database engine; it is therefore governed by exactly the same principles as the outer, “pure”, T-SQL query. All of the regular T-SQL constructs are at your disposal to shape, sort, and correlate, the construction of the delimited string in accordance with your particular requirements.

FOR XML子查询技术与数据库引擎完全集成在一起。 因此,它受与外部“纯” T-SQL查询完全相同的原则支配。 您可以根据自己的特定要求使用所有常规T-SQL构造来定界,构造和关联定界字符串的构造。

Of course, you do not have to restrict the use of the XML subquery to the composition of strings; if the client application expects additional information from the database (such as metadata, or related sets) you can certainly use XML documents to pass the data back to the client as a nested “table”, not just a one-dimensional set. In contrast to returning multiple result sets, where multiple queries would need to be restricted by the same criteria, the XML approach might even significantly reduce the I/O as the data is queried once, with the correlated set returned as a column of the single result set.

当然,您不必将XML子查询的使用限制为字符串的组成。 如果客户端应用程序希望从数据库获得其他信息(例如元数据或相关集合),则可以肯定地使用XML文档将数据作为嵌套的 “表”传递给客户端,而不仅仅是一维集合。 与返回多个结果集(其中多个查询需要受相同条件限制)相比,XML方法甚至可以在查询一次数据时显着减少I / O,而相关集作为单个列的一列返回结果集。

This might come very handy in situations where the consumer is able to process only a single result set (a single table) that has been returned from the data source.

在使用者只能处理从数据源返回的单个结果集(单个表)的情况下,这可能会非常方便。

For instance, the query shown in Figure 2 returns a list of books written by a particular author, including a list of any co-authors.

例如,图2中所示的查询返回由特定作者撰写的书籍列表,其中包括任何共同作者的列表。


select authors.au_lname,authors.au_fname,books= (select titles.title_id,titles.title,titles.price,coauhtors= (select coauthors.au_lname as coau_lname,coauthors.au_fname as coau_fnamefrom dbo.titleauthor as titlecoauthorinner join dbo.authors coauthorson coauthors.au_id = titlecoauthor.au_idwhere (titlecoauthor.title_id = titles.title_id)and (coauthors.au_id <> authors.au_id)for xml path('coauthor'), root('coauthors'), type)from dbo.titleauthorinner join dbo.titleson titleauthor.title_id = titles.title_idwhere (titleauthor.au_id = authors.au_id)for xml path('book'), root('books'), type)from dbo.authorswhere (authors.au_id = '472-27-2349')

Figure 2: Titles written by a particular author, including any other authors.

图2:由特定作者(包括任何其他作者)撰写的标题。

The result of the query, shown in Figure 3 is a single result set, containing an XML column with two additional result sets.

查询结果如图3所示,是一个单一的结果集,其中包含带有两个其他结果集的XML列。


<books><book><title_id>TC7777</title_id><title>Sushi, Anyone?</title><price>14.9900</price><coauhtors><coauthor><coau_lname>O'Leary</coau_lname><coau_fname>Michael</coau_fname></coauthor><coauthor><coau_lname>Yokomoto</coau_lname><coau_fname>Akiko</coau_fname></coauthor></coauhtors></book>
</books>

Figure 3: The XML document with the list of books written by a particular author, including a list of co-authors.

图3:XML文档,其中包含由特定作者撰写的书籍列表,包括合著者列表。

At first glance, the string concatenation technique based on XML composition can seem a bit difficult to understand for something seemingly as easy as “sticking a bunch of strings together”, but it is actually quite intuitive. If you have a good understanding of T-SQL queries, and once you get past the occasional quirkiness of the XPath/XQuery syntax, XML composition will manifest itself as a very useful tool.

乍一看,基于XML组合的字符串连接技术似乎有些难以理解,就像“将一串字符串粘在一起”一样容易,但实际上却非常直观。 如果您对T-SQL查询有一个很好的了解,并且一旦您摆脱了XPath / XQuery语法的偶尔古怪之处,那么XML组合将成为一种非常有用的工具。

In part three of this article I will demonstrate another reliable, and efficient, string concatenation technique using native SQL Server capabilities. Note though, that if your DBA dislikes XML, he is going to absolutely loathe the next approach.

在本文的第三部分中,我将演示使用本机SQL Server功能的另一种可靠,有效的字符串连接技术。 但是请注意,如果您的DBA不喜欢XML,他将绝对讨厌下一种方法。

家庭作业 ( Homework )

In Figure 1 you have seen an example of how XML composition can be used to represent a set of values as a delimited string. It is now your turn to practice this technique, so for your homework I want you to use XML composition to alter the above query in the following way:

在图1中,您看到了一个示例,该示例说明了如何使用XML组合将一组值表示为定界字符串。 现在轮到您练习这种技术了,因此对于您的家庭作业,我希望您使用XML组成以以下方式更改上述查询:

  • In the authors column create a comma-delimited list of each author’s order number (the au_ord column), first name (au_fname), last name (au_lname), phone number (phone), and address attributes (address, city, state and zip).
  • 在作者列中,以逗号分隔的列表列出每个作者的订单号( au_ord列),名字( au_fname ),姓氏( au_lname ),电话号码(电话)和地址属性( 地址 , 城市 , 州和邮编) )。
  • The address will be composed from multiple properties; format it as you see fit, but enclose it in double quotation marks.该地址将由多个属性组成; 格式化为合适的格式,但将其括在双引号中。
  • For books written by multiple authors, make sure the attributes of each author are placed on a separate row of the resulting string.对于由多个作者撰写的书籍,请确保每个作者的属性都放在结果字符串的单独一行中。

As shown in Figure 1, the final result set of your query must still contain one row per book title.

如图1所示,查询的最终结果集每个书名仍必须包含一行。

The pubs sample database used in this article can be found online, at http://www.microsoft.com/en-us/download/details.aspx?id=23654.

可以在http://www.microsoft.com/zh-cn/download/details.aspx?id=23654上在线找到本文中使用的pubs示例数据库。

翻译自: https://www.sqlshack.com/string-concatenation-done-right-part-2-an-effective-technique/

php 字符串串联

php 字符串串联_正确完成字符串串联操作-第2部分-一种有效的技术相关推荐

  1. java 字符串包_包java字符串

    Java核心技术卷I基础知识3.6.3 不可变字符串 3.6.3 不可变字符串 String类没有提供用于修改字符串的方法.如果希望将greeting的内容修改为"Help!",不 ...

  2. python规范化字符串_python中正确的字符串编码规范

    在Python中字符串是不可改变的对象(immutable),因此无法直接修改字符串的某一位字符.一种可行的方式,是将字符串转换为列表,修改列表的元素后,在重新连接为字符串. 示例代码如下:s = ' ...

  3. java的字符串池_翻译-Java字符串池

    正如名字所示:Java中字符串池存储在堆内存中.我们知道java中String是一个特殊的类,我们可以通过new 操作符或者使用双引号""创建一个String对象. Java里的字 ...

  4. c+字符串数组_了解C ++字符串数组

    c+字符串数组 Hey, Folks! So, as programmers, we often deal with Arrays of all data types. We'll cover C++ ...

  5. python字符串命名_从输入字符串到命名复制python 2.7

    你好,我是一个关于巨蟒的初学者,我想知道是否有人要去读一行,然后把它转换成一个名字. 我解释一下我有这两行 MARKS CLASS NAME ID 92 2 Calum 1 对于第一行: line = ...

  6. python字符串 切片_用于切片字符串的Python程序

    python字符串 切片 Given a string and number of characters (N), we have to slice and print the starting N ...

  7. mysql 截取字符串部分值,Mysql字符串截取_获取指定字符串中的数据

    搜索热词 前言:本人遇到一个需求,需要在MysqL的字段中截取一段字符串中的特定字符,类似于正则表达式的截取,苦于没有合适的方法,百度之后终于找到一个合适的方法:substring_index('ww ...

  8. mysql 字符串运算_使用MySQL字符串运算实施精巧化SQL注入攻击

    我们先来看这样一个场景. 有以下表结构: mysql> desc admin; +----------+--------------+------+-----+---------+------- ...

  9. mysql 截取括号内字符串_Mysql字符串截取_获取指定字符串中的数据

    前言:本人遇到一个需求,需要在MySql的字段中截取一段字符串中的特定字符,类似于正则表达式的截取,苦于没有合适的方法,百度之后终于找到一个合适的方法:substring_index('www.sql ...

最新文章

  1. Golang 的跨平台交叉编译浅析
  2. php面试题11(边看边复习刚刚讲的)(array_multisort($arr1,$arr2); 用$arr1来排序$arr2。)...
  3. django模板系统(下)
  4. ZS语音识别(智能语音识别工具)V1.3 绿色版
  5. Mac 系统如何修改python的IDLE默认模块导入路径。
  6. android push php,Android_android push推送相关基本问答总结,通知和消息有什么区别?通 - phpStudy...
  7. Springer LNCS Latex 模板 无法下载
  8. Live Streaming Datasets--网络数据集下载
  9. Java 水印操作的设计与实现
  10. 数据类型和运算符(使用Python的AI编程2部1单元2课)
  11. PDF图片怎么提取?看完这篇你就会了
  12. Unity3D 学习笔记3——了解U3D引擎的操作面板和各种工具
  13. Day43[20180716]_Spark SQL(二)
  14. 时间序列常见模型介绍与实战(SPSS)
  15. Oracle X$BH
  16. Win11如何更改字体样式?Win11更改字体样式的方法
  17. Why We're Breaking Up with CSS-in-JS?
  18. 对 iOS 中 GPU 编程的高度优化的框架 Metal
  19. GIT与SVN的比较
  20. java读取nas文件_Windows store 8 app - 从NAS驱动器播放文件

热门文章

  1. 第5堂:看到词句就会读-上
  2. Qt QDataTime QString 两个类的使用
  3. Jzoj4627 斐波那契数列
  4. Android多线程的使用
  5. 关于c:if没有c:else解决方案
  6. Spring2.5事务配置的5种方法
  7. 用ZedGraph作图表(一)
  8. LeetCode(566)——重塑矩阵(JavaScript)
  9. 快速删除node_modules文件夹!!!
  10. JavaScript学习(七十二)—严格模式