0

I'm doing a simple INSERT query into my database. The column id have auto-generated ID and i need it for another query. I read i can get the generated id using a parameter in output direction, so i wrote this code:

string id;
queryString = "INSERT INTO tr_text (form, item, enabled, programID) VALUES (@myForm, @myItem, 1, @myProgramID)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(queryString, connection);
    connection.Open();
    command.CommandText = queryString;
    command.Parameters.Add("@myForm", SqlDbType.NVarChar, 50).Value = form;
    command.Parameters.Add("@myItem", SqlDbType.NVarChar, 50).Value = item;
    command.Parameters.Add("@myProgramID", SqlDbType.Int).Value = 1;
    SqlParameter param = new SqlParameter("@id", SqlDbType.Int, 0, "id");
    param.Direction = ParameterDirection.Output;
    command.Parameters.Add(param);
    command.ExecuteNonQuery();
    id = command.Parameters["@id"].Value.ToString();
 }

My query is executed correctly (i have the correct new record in my database) but my id variable is still empty! how can i make that code work?

4

2 回答 2

3

请像这样更改您的查询;

 INSERT INTO tr_text (form, item, enabled, programID) 
 OUTPUT INSERTED.ID
 VALUES (@myForm, @myItem, 1, @myProgramID)

并像那样使用 ExecuteScalar() 而不是 ExecuteNonQuery() ;

 Int32 id= (Int32) command.ExecuteScalar();
于 2013-06-13T08:28:23.667 回答
1

更改您的查询,因为您没有将 @id 设置为任何值

INSERT INTO tr_text (form, item, enabled, programID) VALUES (@myForm, @myItem, 1, @myProgramID) 
set @id = SCOPE_IDENTITY();
于 2013-06-13T08:28:17.293 回答