如何将插入的记录的ID返回给C#

时间:2013-08-26 19:23:55

标签: c# sql-server

我有这个存储过程:

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。

格雷格

3 个答案:

答案 0 :(得分:5)

检查ExecuteNonQuery()上的文档:

  

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

(强调我的)

如果您想获取信息,可以选择以下几种方式:

  1. RETURN更改为SELECT,将ExecuteNonQuery()更改为ExecuteScalar()
  2. 使用OUTPUT parameter

答案 1 :(得分:0)

添加Joel的回复 请尝试使用ExecuteScalar

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

答案 2 :(得分:0)

这会对你有所帮助。如果插入了新行,则该函数返回新的Identity列值,失败时返回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;

}