【问题标题】:Stored procedure called from C# doesn't update record从 C# 调用的存储过程不更新记录
【发布时间】:2012-01-04 09:56:35
【问题描述】:

我编写了一个简单的存储过程来更新一条不起作用的记录,但我不知道为什么。不会抛出异常,但记录也不会更新。

见下面的代码:

public int IMGId;

protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string result = "";
        string sSQL = "usp_imageloader_update";


        using (SqlConnection dbConnection = new SqlConnection(CKS_app_settings.sql_conn_string_db))
        {
            // SqlTransaction tn=null;   
            try
            {
                dbConnection.Open();
                //start Transaction
                // tn = dbConnection.BeginTransaction();
                SqlCommand command = new SqlCommand(sSQL, dbConnection);
                //command.Transaction = tn;
                command.CommandText = sSQL;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandTimeout = 1024;
                command.Parameters.AddWithValue("@p_image_id", IMGId);
                command.Parameters.AddWithValue("@p_url", txtUrl.Text);
                command.Parameters.AddWithValue("@p_alt_text", txtAlt.Text);
                //command.Parameters.AddWithValue("@p_filepath", File1.Value);
                //command.Parameters.AddWithValue("@p_cntr_id", str_id);
                int rowsAffected = command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
               // throw ex;

                //If it failed for whatever reason, rollback the //transaction
                //tn.Rollback();                          
                //No need to throw because we are at a top level call and //nothing is handling exceptions
                result = ex.InnerException.Message;
            }
        }

SQL SERVER 中的存储过程

USE [smsdb_test_griffin2]
GO
/****** Object:  StoredProcedure [dbo].[usp_imageloader_update]    Script Date: 01/04/2012   09:05:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER    procedure [dbo].[usp_imageloader_update]
@p_image_id INT,
@p_url  VARCHAR(255),
@p_alt_text VARCHAR(255)
as 

UPDATE Image_Library_UK 
SET  
Url=@p_url,
Alt_text=@p_alt_text 

WHERE Image_id=@p_image_id

【问题讨论】:

  • 如果您的 SP 单独执行,即不是从您的 C# 代码中执行,它是否可以工作?
  • 你说的T-SQL? GO 在 T-SQL 中的存储过程中不起作用。
  • 您是否尝试过在 SQL 管理中使用 C# 中传递的值执行 exec 过程?
  • 可能是 btnUpdate 的点击处理程序被重置/取消设置。
  • “UPDATE Image_Library_UK”更新表。

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


【解决方案1】:

单独尝试过,假设它有效(并且没有明显的错误),我会假设您的参数之一设置不正确。可能是 IMGid 不正确 - 这会产生这种效果 - 或者可能是 url 和 alttext 已经被页面加载重置为它们的值。

检查调用点的值。您可能需要使用 !Page.IsPostBack 在回发时不重置这些值。您可能需要使用 request 变量来访问它们 - 它确实取决于您的其余代码。

【讨论】:

  • 我为 ID 硬编码了一个 int 值,并且存储过程正常工作。我想从我的代码中获取 id 时出了点问题。感谢所有帮助过的人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多