Home Backend Development XML/RSS Tutorial Detailed explanation of the sample code for SQL operations on Xml fields (picture)

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

Mar 09, 2017 pm 05:10 PM

 

T-Sql操作Xml数据

一、前言

SQL Server 2005 引入了一种称为 XML 的本机数据类型。用户可以创建这样的表,它在关系列之外还有一个或多个 XML 类型的列;此外,还允许带有变量和参数。为了更好地支持 XML 模型特征(例如文档顺序和递归结构),XML 值以内部格式存储为大型二进制对象 (BLOB)。

用户将一个XML数据存入数据库的时候,可以使用这个XML的字符串,SQL Server会自动的将这个字符串转化为XML类型,并存储到数据库中。

随着SQL Server 对XML字段的支持,相应的,T-SQL语句也提供了大量对XML操作的功能来配合SQL Server中XML字段的使用。本文主要说明如何使用SQL语句对XML进行操作。

二、定义XML字段

在进行数据库的设计中,我们可以在表设计器中,很方便的将一个字段定义为XML类型。需要注意的是,XML字段不能用来作为主键或者索引键。同样,我们也可以使用SQL语句来创建使用XML字段的数据表,下面的语句创建一个名为“docs”的表,该表带有整型主键“pk”和非类型化的 XML 列“xCol”:

CREATE TABLE docs (pk INT PRIMARY KEY, xCol XML not null)
Copy after login

XML类型除了在表中使用,还可以在存储过程、事务、函数等中出现。下面我们来完成我们对XML操作的第一步,使用SQL语句定义一个XML类型的数据,并为它赋值:

declare @xmlDoc xml;
set @xmlDoc=&#39;<book id="0001">
<title>C Program</title>
<author>David</author>
<price>21</price>
</book>&#39;
Copy after login

三、查询操作

在定义了一个XML类型的数据之后,我们最常用的就是查询操作,下面我们来介绍如何使用SQL语句来进行查询操作的。

在T-Sql中,提供了两个对XML类型数据进行查询的函数,分别是query(xquery)和value(xquery, dataType),其中,query(xquery)得到的是带有标签的数据,而value(xquery, dataType)得到的则是标签的内容。接下类我们分别使用这两个函数来进行查询。

1、使用query(xquery) 查询

我们需要得到书的标题(title),使用query(xquery)来进行查询,查询语句为:

select @xmlDoc.query(&#39;/book/title&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

2、使用value(xquery, dataType) 查询

同样是得到书的标题,使用value函数,需要指明两个参数,一个为xquery, 另一个为得到数据的类型。看下面的查询语句:

select @xmlDoc.value(&#39;(/book/title)[1]&#39;, &#39;nvarchar(max)&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

3、查询属性值

无论是使用query还是value,都可以很容易的得到一个节点的某个属性值,例如,我们很希望得到book节点的id,我们这里使用value方法进行查询,语句为:

select @xmlDoc.value(&#39;(/book/@id)[1]&#39;, &#39;nvarchar(max)&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

4、使用xpath进行查询

xpath是.net平台下支持的,统一的Xml查询语句。使用XPath可以方便的得到想要的节点,而不用使用where语句。例如,我们在@xmlDoc中添加了另外一个节点,重新定义如下:

set @xmlDoc=&#39;<root>
<book id="0001">
<title>C# Program</title>
<author>Jerry</author>
<price>50</price>
</book>
<book id="0002">
<title>Java Program</title>
<author>Tom</author>
<price>49</price>
</book>
</root>&#39;
Copy after login

--得到id为0002的book节点

select @xmlDoc.query(&#39;(/root/book[@id="0002"])&#39;)
Copy after login

上面的语句可以独立运行,它得到的是id为0002的节点。运行结果如下图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)[6]

四、修改操作

SQL的修改操作包括更新和删除。SQL提供了modify()方法,实现对Xml的修改操作。modify方法的参数为XML修改语言。XML修改语言类似于SQL 的Insert、Delete、UpDate,但并不一样。

1、修改节点值

我们希望将id为0001的书的价钱(price)修改为100, 我们就可以使用modify方法。代码如下:

set @xmlDoc.modify(&#39;replace value of (/root/book[@id=0001]/price/text())[1] with "100"&#39;)
--得到id为0001的book节点
select @xmlDoc.query(&#39;(/root/book[@id="0001"])&#39;)
Copy after login

注意:modify方法必须出现在set的后面。运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

2、删除节点

接下来我们来删除id为0002的节点,代码如下:

--删除节点id为0002的book节点
set @xmlDoc.modify(&#39;delete /root/book[@id=0002]&#39;)
select @xmlDoc
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

3、添加节点

很多时候,我们还需要向xml里面添加节点,这个时候我们一样需要使用modify方法。下面我们就向id为0001的book节点中添加一个ISBN节点,代码如下:

--添加节点

set @xmlDoc.modify(&#39;insert <isbn>78-596-134</isbn> before (/root/book[@id=0001]/price)[1]&#39;)
select @xmlDoc.query(&#39;(/root/book[@id="0001"]/isbn)&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

4、添加和删除属性

当你学会对节点的操作以后,你会发现,很多时候,我们需要对节点进行操作。这个时候我们依然使用modify方法,例如,向id为0001的book节点中添加一个date属性,用来存储出版时间。代码如下:

--添加属性

set @xmlDoc.modify(&#39;insert attribute date{"2008-11-27"} into (/root/book[@id=0001])[1]&#39;)
select @xmlDoc.query(&#39;(/root/book[@id="0001"])&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

如果你想同时向一个节点添加多个属性,你可以使用一个属性的集合来实现,属性的集合可以写成:(attribute date{"2008-11-27"}, attribute year{"2008"}),你还可以添加更多。这里就不再举例了。

5、删除属性

删除一个属性,例如删除id为0001 的book节点的id属性,我们可以使用如下代码:

--删除属性

set @xmlDoc.modify(&#39;delete root/book[@id="0001"]/@id&#39;)
select @xmlDoc.query(&#39;(/root/book)[1]&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

6、修改属性

修改属性值也是很常用的,例如把id为0001的book节点的id属性修改为0005,我们可以使用如下代码:

--修改属性

set @xmlDoc.modify(&#39;replace value of (root/book[@id="0001"]/@id)[1] with "0005"&#39;)
select @xmlDoc.query(&#39;(/root/book)[1]&#39;)
Copy after login

运行结果如图:

Detailed explanation of the sample code for SQL operations on Xml fields (picture)

OK,经过上面的学习,相信你已经可以很好的在SQL中使用Xml类型了,下面是我们没有提到的,你可以去其它地方查阅:exist()方法,用来判断指定的节点是否存在,返回值为true或false; nodes()方法,用来把一组由一个查询返回的节点转换成一个类似于结果集的表中的一组记录行。

 


The above is the detailed content of Detailed explanation of the sample code for SQL operations on Xml fields (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

What does the identity attribute in SQL mean? What does the identity attribute in SQL mean? Feb 19, 2024 am 11:24 AM

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

Database technology competition: What are the differences between Oracle and SQL? Database technology competition: What are the differences between Oracle and SQL? Mar 09, 2024 am 08:30 AM

Database technology competition: What are the differences between Oracle and SQL? In the database field, Oracle and SQL Server are two highly respected relational database management systems. Although they both belong to the category of relational databases, there are many differences between them. In this article, we will delve into the differences between Oracle and SQL Server, as well as their features and advantages in practical applications. First of all, there are differences in syntax between Oracle and SQL Server.

See all articles