如果你正在使用SQL 2008,你可以创建一个接受表值参数(TVP)的存储过程,并使用ADO.net执行存储过程并将数据表传递给它:
首先,在SQL服务器中,你需要创建该类型:
CREATE TYPE [dbo].[udt_UserId] AS TABLE(
[UserId] [int] NULL
)
接下来,您需要编写一个存储过程,该存储过程接受此类型作为参数:
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
@UserIdList udt_UserId READONLY
)
AS
BEGIN
SELECT userId, username
FROM Users
WHERE userId IN (SELECT UserId FROM @UserIDList)
END
现在从.net开始,由于它还不支持表值参数,您不能使用LINQ;因此,您必须编写一个函数,该函数执行纯老式的ADO.net,接受一个DataTable,并将其传递给存储过程:我编写了一个通用函数,可以为任何存储过程执行此操作,只要它仅采用一个表类型参数,而不管它是什么;
public static int ExecStoredProcWithTVP(DbConnection connection, string storedProcedureName, string tableName, string tableTypeName, DataTable dt)
{
using (SqlConnection conn = new SqlConnection(connection.ConnectionString))
{
SqlCommand cmd = new SqlCommand(storedProcedureName, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p = cmd.Parameters.AddWithValue(tableName, dt);
p.SqlDbType = SqlDbType.Structured;
p.TypeName = tableTypeName;
conn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
return rowsAffected;
}
}
接下来,您可以编写使用此实用程序函数和存储过程的实际名称的DAL函数;以您问题中的示例为基础,以下是代码示例:
public int usp_DoSomethingWithTableTypedParameter(List<UserID> userIdList)
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(int));
foreach (var userId in updateList)
{
dt.Rows.Add(new object[] { userId });
}
int rowsAffected = ExecStoredProcWithTVP(Connection, "usp_DoSomethingWithTableTypedParameter", "@UserIdList", "udt_UserId", dt);
return rowsAffected;
}
请注意上面的“connection”参数 - 我实际上在部分DataContext类中使用这种类型的函数来扩展LINQ DataContext与我的TVP功能,并且仍然使用(using var context = new MyDataContext())语法来调用这些方法。
只有当您使用SQL Server 2008时,此方法才有效 - 希望您正在使用,如果没有,这可能是升级的一个很好的理由!当然,在大多数情况下和大型生产环境中,这并不容易,但值得一提的是,如果您拥有可用的技术,我认为这是最佳方法。