为什么我的SQL CLR存储过程调用声称我没有提供参数

本文关键字:参数 SQL 我的 CLR 存储过程 调用 为什么 | 更新日期: 2023-09-27 17:57:34

在CLR过程中,我有以下方法:

private static void EndOwnershipForTeam(long assetId, int teamId)
{
    const string storedProcedureName = @"up_RemoveAssetOwnershipFromTeam";
    using (var connection = new SqlConnection("context connection=true"))
    using (var command = new SqlCommand(storedProcedureName, connection))
    {
        command.Parameters.AddWithValue("assetId", assetId);
        command.Parameters.AddWithValue("teamId", teamId);
        connection.Open();
        command.ExecuteNonQuery();
    }
}

当我运行这个方法时,我得到了以下错误:

消息6522,级别16,状态1,过程cp_RemoveAsset,第0行

在用户定义例程或聚合"的执行过程中出现.NET Framework错误;cp_RemoveAsset":

System.Data.SqlClient.SqlException:过程或函数"up_RemoveAssetOwnershipFromTeam"需要参数"@assetId",但未提供该参数。

System.Data.SqlClient.SqlException:

位于System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔breakConnection)

在System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(布尔sendToPipe)

在System.Data.SqlClient.SqlCommand.InteralExecuteNonQuery(DbAsyncResult结果,字符串methodName,布尔sendToPipe)

位于System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

在StoredProcedures.EndOwnershipForTeam(Int64资产ID,Int32团队ID)

在StoredProcedures.cp_MoveAsset(SqlInt32 userId,SqlString xaid)

既然我的代码正在提供参数(通过SqlContext.Pipe.Send()调用显示输出来验证);I’我没有提供一个参数?

为什么我的SQL CLR存储过程调用声称我没有提供参数

看起来,您的代码正在指示SQL Server尝试执行以下操作:

up_RemoveAssetOwnershipFromTeam

换句话说,就是没有提供任何参数的过程。

要连接参数,您需要指定CommandType.StoredProcedure,或者显式连接命令参数:

// option 1
private static void EndOwnershipForTeam(long assetId, int teamId)
{
    const string storedProcedureName = @"up_RemoveAssetOwnershipFromTeam";
    using (var connection = new SqlConnection("context connection=true"))
    using (var command = new SqlCommand(storedProcedureName, connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.AddWithValue("assetId", assetId);
        command.Parameters.AddWithValue("teamId", teamId);
        connection.Open();
        command.ExecuteNonQuery();
    }
}
// option 2
private static void EndOwnershipForTeam(long assetId, int teamId)
{
    const string sql = @"exec up_RemoveAssetOwnershipFromTeam @assetId, @teamId";
    using (var connection = new SqlConnection("context connection=true"))
    using (var command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@assetId", assetId);
        command.Parameters.AddWithValue("@teamId", teamId);
        connection.Open();
        command.ExecuteNonQuery();
    }
}

您在行中遗漏了@符号

command.Parameters.AddWithValue("assetId", assetId);
command.Parameters.AddWithValue("teamId", teamId);

它们应该是

command.Parameters.AddWithValue("@assetId", assetId);
command.Parameters.AddWithValue("@teamId", teamId);
  1. 您省略了前缀"@"
  2. 为sql server和/或数据库配置的默认排序规则是什么?若它是区分大小写的,那个么您需要完全匹配大小写