【问题标题】:How to return the ID of the Inserted Record to C#如何将插入记录的ID返回给C#
【发布时间】:2013-08-29 09:04:43
【问题描述】:

我有这个存储过程:

Insert into dbo.file_row (file_sub_type) values (@file_sub_type)
DECLARE @result int;
SET @result = SCOPE_IDENTITY()
RETURN @result;

这可以很好地返回 SSMS 中的 id。但是,当我从 C# 调用它时,它返回 -1。

var connection = GetSqlConnection();
connection.Open();

SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "InsertInto_file_row";
command.Parameters.Add(new SqlParameter("@file_sub_type", fileType));

int result = command.ExecuteNonQuery();
connection.Close();
return result;

我看不出我做错了什么。我只需要插入记录的 ID。

格雷格

【问题讨论】:

  • 使用 ExecuteScalar - ExecuteNonQuery 将返回受影响的行。

标签: c# sql-server


【解决方案1】:

查看ExecuteNonQuery()上的文档:

针对连接执行 Transact-SQL 语句并返回受影响的行数。

(强调我的)

如果您想取回信息,您有几个选择:

  1. RETURN 更改为SELECTExecuteNonQuery() 更改为ExecuteScalar()
  2. 使用OUTPUT parameter

【讨论】:

  • 8 年后,我将此标记为答案。抱歉耽搁了。
【解决方案2】:

补充乔尔的回应 改用 ExecuteScalar

执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。 (覆盖 DbCommand.ExecuteScalar()。)

【讨论】:

    【解决方案3】:

    这将对您有所帮助。如果插入了新行,则该函数返回新的标识列值,失败时返回 0。来自MSDN

    static public int AddProductCategory(string newName, string connString)
    {
       Int32 newProdID = 0;
       string sql =
        "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
        + "SELECT CAST(scope_identity() AS int)";
       using (SqlConnection conn = new SqlConnection(connString))
      {
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar);
        cmd.Parameters["@name"].Value = newName;
        try
        {
            conn.Open();
            newProdID = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    return (int)newProdID;
    

    }

    【讨论】:

      【解决方案4】:
      public int AddProductCategory(string newName, string connString)
          {
                string sql =
          "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); "
          + "SELECT CAST(scope_identity() AS int)";
              using (SqlConnection con = new SqlConnection(conString))
              {
                  using (SqlCommand cmd = new SqlCommand(query, con))
                  {
                      cmd.Parameters.AddWithValue("@Name", newName);
                     
                      con.Open();
                      latestInsertedId = (int)cmd.ExecuteScalar();
                      con.Close();
                  }
                  return latestInsertedId ;
              }
          }
      

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 2011-05-05
      • 1970-01-01
      • 2014-10-19
      • 2015-06-08
      相关资源
      最近更新 更多