search
HomeDatabaseMysql TutorialSqlServer参数化查询之where in和like实现之xml和DataTable传参

在上一篇Sql Server参数化查询之where in和like实现详解中介绍了在Sql Server使用参数化查询where in的几种实现方案,遗漏了xml和表值参数,这里做一个补充

方案5 使用xml参数

对sql server xml类型参数不熟悉的童鞋需要先了解下XQuery概念,这里简单提下XQuery 是用来从 XML 文档查找和提取元素及属性的语言,简单说就是用于查询xml的语言说到这就会牵着到XPath,其实XPath是XQuery的一个子集,XQuery 1.0 和 XPath 2.0 共享相同的数据模型,并支持相同的函数和运算符,XPath的方法均适用于XQuery,假如您已经学习了 XPath,那么学习 XQuery 也不会有问题。详见

XQuery概念了解后需要进一步了解下Sql Server对xml的支持函数,主要为、、、、 ,详见

使用xml方式实现where in时有两种实现方式,使用value和exist,在这里推荐使用exist方法,msdn是这样描述的:

D.使用 exist() 方法而不使用 value() 方法
由于性能原因,不在谓词中使用 value() 方法与关系值进行比较,而改用具有 sql:column() 的 exist()。


使用xml的value方法实现(不推荐)
代码如下:
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
string xml = @"

1
2
5
";
SqlCommand comm = conn.CreateCommand();
//不推荐使用value方法实现,性能相对exist要低
comm.CommandText = @"select * from Users
where exists
(
select 1 from @xml.nodes('/root/UserID') as T(c)
where T.c.value('text()[1]','int')= Users.UserID
)";

//也可以这样写,结果是一样的
//comm.CommandText = @"select * from Users
// where UserID in
// (
// select T.c.value('text()[1]','int') from @xml.nodes('/root/UserID') as T(c)
// )
comm.Parameters.Add(new SqlParameter("@xml", SqlDbType.Xml) { Value = xml });
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
adapter.SelectCommand = comm;
adapter.Fill(dt);
}
}

使用xml的exist方法实现(推荐)
代码如下:
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
string xml = @"

1
2
5
";
SqlCommand comm = conn.CreateCommand();

//使用xml的exist方法实现这样能够获得较高的性能
comm.CommandText = @"select * from Users where @xml.exist('/root/UserID[text()=sql:column(""UserID"")]')=1";
comm.Parameters.Add(new SqlParameter("@xml", SqlDbType.Xml) { Value = xml });
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
adapter.SelectCommand = comm;
adapter.Fill(dt);
}
}

列举下不同xml结构的查询方法示例,在实际使用中经常因为不同的xml结构经常伤透了脑筋
代码如下:
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
string xml = @"


1


2


5

";
SqlCommand comm = conn.CreateCommand();

//不推荐使用value方法实现,性能相对exist要低
comm.CommandText = @"select * from Users
where UserID in
(
select T.c.value('UserID[1]','int') from @xml.nodes('/root/User') as T(c)
)";
//也可以这样写,结果是一样的
//comm.CommandText = @"select * from Users
// where exists
// (
// select 1 from @xml.nodes('/root/User') as T(c)
// where T.c.value('UserID[1]','int') = Users.UserID
// )";
comm.Parameters.Add(new SqlParameter("@xml", SqlDbType.Xml) { Value = xml });
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
adapter.SelectCommand = comm;
adapter.Fill(dt);
}
}

代码如下:
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
string xml = @"


1


2


5

";
SqlCommand comm = conn.CreateCommand();
//使用xml的exist方法实现这样能够获得较高的性能
comm.CommandText = @"select * from Users where @xml.exist('/root/User[UserID=sql:column(""UserID"")]')=1";

comm.Parameters.Add(new SqlParameter("@xml", SqlDbType.Xml) { Value = xml });
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
adapter.SelectCommand = comm;
adapter.Fill(dt);
}
}

使用xml参数时需要注意点:

  1.不同于SQL语句默认不区分大小写,xml的XQuery表达式是严格区分大小写的,所以书写时一定注意大小写问题

  2.使用exist时sql:column() 中的列名须使用双引号,如sql:column("UserID"),若非要使用单引号需要连续输入两个单引号 sql:column(''UserID'')

  3.不管是where in或是其他情况下使用xml查询时能用exist(看清楚了不是sql里的exists)方法就用exist方法,我们不去刻意追求性能的优化,但能顺手为之的话何乐而不为呢。

方案6 使用表值参数(Table-Valued Parameters 简称TVP Sql Server2008开始支持)
按照msdn描述TVP参数在数据量小于1000时有着很出色的性能,关于TVP可以参考

这里主要介绍如何使用TVP实现DataTable集合传参实现where in
1.使用表值参数,首先在数据库创建表值函数
create type IntCollectionTVP as Table(ID int)
2.表值函数创建好后进行c#调用,
注意点:
  1.需要SqlParameter中的SqlDbType设置为SqlDbType.Structured然后需要设置TypeName为在数据库中创建的表值函数名,本示例中为IntCollectionTVP
  2.构造的DataTabel列数必须和表值函数定义的一样,具体列名随意,无需和表值函数定义的列名一致,数据类型可以随意,但还是建议和表值类型定义的保持一致,一来省去隐式类型转换,二来可以在初始化DataTabel时就将不合法的参数过滤掉
  3.建议定义tvp的时候最好查询条件里的类型和tvp对应字段类型保持一致,这样可以避免隐式类型转换带来的性能损失
代码如下:
DataTable resultDt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand comm = conn.CreateCommand();
comm.CommandText = @"select * from Users(nolock)
where exists
(
select 1 from @MyTvp tvp
where tvp.ID=Users.UserID
)";
//构造需要传参的TVP DataTable
DataTable tvpDt = new DataTable();
//为表添加列,列数需要和表值函数IntCollectionTVP保值一致,列名可以不一样
tvpDt.Columns.Add("myid", typeof(int));
//添加数据
tvpDt.Rows.Add(1);
tvpDt.Rows.Add(2);
tvpDt.Rows.Add(3);
tvpDt.Rows.Add(4);
//这里的TypeName对应我们定义的表值函数名
comm.Parameters.Add(new SqlParameter("@MyTvp", SqlDbType.Structured) { Value = tvpDt, TypeName = "IntCollectionTVP" });
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
adapter.SelectCommand = comm;
adapter.Fill(resultDt);
}
}

总结:
至此,一共总结了6六种where参数化实现,分别如下
1.使用CHARINDEX或like实现where in 参数化
2.使用exec动态执行SQl实现where in 参数化
3.为每一个参数生成一个参数实现where in 参数化
4.使用临时表实现where in 参数化
5.使用xml参数实现where in 参数化
6.使用表值参数(TVP)实现where in 参数化
其中前4种在Sql Server参数化查询之where in和like实现详解 一文中进行了列举和示例
6种方法,6种思路,
其中方法1 等于完全弃用了索引,若无特殊需要不建议采用,
方法2 本质上合拼SQL没啥区别与其用方法2自欺其人还不如直接拼接SQL来的实惠
方法3 受参数个数(做多2100个参数)限制,而且若传的参数过多性能如何有待验证,可以酌情使用
方法4 示例中采用的临时表,其实可以换成表变量性能也许会更好些,不过写法上有些繁琐,可以具体的封装成一个函数会好些(推荐)
方法5 使用xml传参,既然有这种类型说明性能上应该还不错,其它会比拼接SQL好很多,使用上也还比较方便,不过需要开发人员对xml查询有一定了解才行(推荐)
方法6 tvp方式sql server2008以后才可以使用,很好很强大,若只为where in 的话可以定义几个tvp where in问题就很容易解决了,而且是强类型也更容易理解(推荐)
不好去评论具体那种方法最好,还是那句老话合适的最好。

此文章属懒惰的肥兔原创

Statement
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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools