数据库
首页 > 数据库> > MSSQL 表值参数的使用

MSSQL 表值参数的使用

作者:互联网

数据库部分

use TestDb;

/* 创建一个自定义类型 */
go

create type T_ID as Table (
	Id bigint not null ,
        [State] int not null,
)

go

/* 创建 存储过程 */
CREATE PROCEDURE SP_CountProduct
	@product dbo.T_ID readonly,
	@createBy bigint ,
	@createName nvarchar(50)
AS
BEGIN
	
	if not exists (select p.* from Products p inner join @product p1 on p1.Id = p.Id)
	begin
		return -1;
	end
	declare @cnt int;
        select @cnt = COUNT(*) from from Products p 
        inner join @product p1 on p1.Id = p.Id and p.[State] != p1.[State];
        return @cnt;
END


go 

/*授权 自定义类型 的执行权限 */
grant exec on TYPE::Tetst.dbo.T_ID to  dbuser

go

/*授权 存储过程 的执行权限 */
grant exec on Tetst.dbo.CountProduct to  dbuser


代码执行


//using Dapper

using (var dt = new DataTable())
{
    dt.Columns.Add("Id", typeof(long));

    foreach (var id in dto.Ids)
    {
        dt.Rows.Add(id);
    }
    var parameters = new DbParameter[] 
    {      
      // SqlDbType :SqlDbType.Structured, TypeName : 我们创建的自定义类型
      new SqlParameter("@product", SqlDbType.Structured) {TypeName = "T_ID", Value = dt, }
      new SqlParameter {ParameterName = "@createBy", Value = session.UserId, DbType = DbType.Int64,}, 
      new SqlParameter {ParameterName = "@createName", Value = session.UserName ?? string.Empty, Size = 50, DbType = DbType.String}
    };
    var r = await _dbConnection.ExecuteNonQueryAsync("SP_CountProduct", CommandType.StoredProcedure, parameters);
}

标签:product,p1,表值,Id,参数,go,new,dt,MSSQL
来源: https://www.cnblogs.com/jzblive/p/14842364.html