SqlServer教程

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);
}
这篇关于MSSQL 表值参数的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!