TVP(全称 :Table-Valued Parameter)
叫做表值参数(Table-Valued Parameter)是SQL2008的一个新特性。顾名思义,表值参数表示你可以把一个表类型作为参数传递到函数或存储过程里。
实例讲解:
第一步:创建一个Type类型和写入数据的原始表结构相同
CREATE TYPE [dbo].[TestTVP] AS TABLE( [TID] [bigint] NOT NULL, [DepID] [nvarchar](100) NOT NULL, [DepName] [nvarchar](512) NOT NULL, [DataChange_CreateTime] [datetime] NOT NULL, [DataChange_LastTime] [datetime] NOT NULL, PRIMARY KEY CLUSTERED ( [TID] ASC )WITH (IGNORE_DUP_KEY = OFF) ) GO
第二步:创建存储过程
CREATE PROCEDURE [dbo].[SP_TestTVP_I] ( @TestTVP TestTVP READONLY ) AS DECLARE @retcode int, @rowcount int SET LOCK_TIMEOUT 1000 SET NOCOUNT ON INSERT INTO 原始表名(列) SELECT 表参数列 FROM @TestTVP
第三步:C#代码使用
//需要构建Table数据或者从表中查询的数据返回到Table SqlConnection connection = new SqlConnection(""); SqlCommand command = new SqlCommand(); command.Connection = connection; connection.Open(); command.CommandText = "[dbo].[SP_TestTVP_I]"; command.CommandType = CommandType.StoredProcedure; SqlParameter tvpParam = command.Parameters.AddWithValue("@TestTVP", insertTab); tvpParam.SqlDbType = SqlDbType.Structured; command.ExecuteNonQuery(); command.Parameters.Clear(); connection.Close();
结束。。。
其他批量Insert,update,delete脚本SQL
insert into select * from table
update tab1 set tab1.col=tab2.col2 from tab1,tab2 where tab1.colA=tab2.colB
update tab1 set tab1.col=tab2.col2 from tab1 join tab2 on tab1.colA=tab2.colB
delete from t1 from t1,t2 where t1.id=t2.id
delete from t1 from t1 inner join t2 on t1.id = t2.tid