简体   繁体   English

使用一个插入语句为多个值填充 ado.net 中的表值参数?

[英]Populate a table-valued parameter in ado.net with ONE insert statement for multiple values?

I have some C# code that is populating a TVP and then calling a stored procedure in SQL Server where it passes in that TVP.我有一些 C# 代码正在填充 TVP,然后在 SQL Server 中调用存储过程,并在其中传递该 TVP。 It utilizes the standard ADO.NET DataTable and the Rows.Add to populate the rows.它利用标准的 ADO.NET DataTable 和Rows.Add来填充行。

When the sqlCommand.ExecuteNonQuery() runs, if you capture a SQL trace in SQL Profiler, you will see it something like this, where it populates each row of the TVP in separate insert statements.sqlCommand.ExecuteNonQuery()运行时,如果您在 SQL Profiler 中捕获 SQL 跟踪,您将看到类似这样的内容,它在单独的插入语句中填充 TVP 的每一行。

declare @p1 dbo.BigIntTable -- This is a table type

insert into @p1 values(1)
insert into @p1 values(2)
insert into @p1 values(3)
insert into @p1 values(4)
insert into @p1 values(5)

exec dbo.MyProc @InputTVP=@p1
go

I want it to insert all the values in one statement, as seen below.我希望它在一个语句中插入所有值,如下所示。 The example below is valid SQL and performs much better than the above generated by ADO.NET.下面的示例是有效的 SQL,并且比 ADO.NET 生成的上述示例执行得更好。 Any ideas?有任何想法吗?

declare @p1 dbo.BigIntTable -- This is a table type

insert into @p1 
values
 (1)
,(2)
,(3)
,(4)
,(5)

exec dbo.MyProc @InputTVP=@p1
go

Profiler shows you not what the client actually sent , but a kind of TSQL reproduction batch that you could run to do the same thing. Profiler 向您展示的不是客户端实际发送的内容,而是一种您可以运行以执行相同操作的 TSQL 复制批处理。

Table-Valued Parameters are a feature of the TDS network protocol , as well as the SQL Server Database Engine.表值参数是TDS 网络协议以及 SQL Server 数据库引擎的一项功能 And clients will send the data directly using TDS, and not in seperate INSERT statements.客户端将直接使用 TDS 发送数据,而不是在单独的 INSERT 语句中。

If you run Profiler, you'll see that there aren't separate SQL:StmtCompleted events for inserting each row into the TVP.如果您运行 Profiler,您将看到没有单独的 SQL:StmtCompleted 事件用于将每一行插入到 TVP 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM