数据库部分
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);
}