Sql Server存储过程不从MVC执行

时间:2015-07-21 05:08:28

标签: c# sql-server asp.net-mvc stored-procedures

我正在尝试从Asp.Net MVC项目在我的Sql Server数据库中执行存储过程。我已将其设置为可以将其用于测试目的,这就是为什么变量“procedureTest”是一个常量值(我知道“2044”是我数据库中的现有记录)。一旦我成功完成,我将改变这一点。此外,我知道我的存储过程工作,因为我已成功在Sql Server Management Studio中执行它。该过程的任务是将ID从一个表添加到另一个表,但我还没有看到它出现在此表中。我的catch区块中没有收到错误,所以此刻我有点迷失了。我绝对可以帮助你。

try
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        int procedureTest = 2044;

        var command = new SqlCommand("SELECT ID FROM Images WHERE ID = @id", connection);
        var paramDate = new SqlParameter("@id", procedureTest);
        command.Parameters.Add(paramDate);
        var reader = command.ExecuteReader();

        while (reader.Read())
        {
            var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
            var paramId = new SqlParameter("@ID", reader.GetInt32(0));
            storedProcCommand.Parameters.Add(paramId);
            command.ExecuteNonQuery();
        }
    }
}
catch (Exception e)
{
    string exceptionCause = String.Format("An error occurred: '{0}'", e);
    System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
} 

存储过程:

CREATE PROCEDURE addToNotificationTable @ID int
AS
Insert NotificationTable (ID)
SELECT ID 
FROM Images
Where ID = @ID

2 个答案:

答案 0 :(得分:1)

像这样改变你的代码

while (reader.Read())
        {
            var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
            var paramId = new SqlParameter("@ID", reader.GetInt32(0));
            storedProcCommand.Parameters.Add(paramId);
            storedProcCommand.ExecuteNonQuery();
        }

答案 1 :(得分:0)

首先,您错过了指定命令类型。在SqlCommand中使用EXEC也不是一种正确的方法。

请尝试使用以下代码

while (reader.Read())
        {
            using(SqlCommand storedProcCommand = new SqlCommand("addToNotificationTable", connection)) //Specify only the SP name
            { 
                storedProcCommand.CommandType = CommandType.StoredProcedure; //Indicates that Command to be executed is a stored procedure no a query
                var paramId = new SqlParameter("@ID", reader.GetInt32(0));
                storedProcCommand.Parameters.Add(paramId);
                storedProcCommand.ExecuteNonQuery()
            }
        }

由于您在while循环中调用sp,因此请在using() { }中包装代码以在每次迭代后自动释放命令对象