I need a stored procedure that excecutes a INSERT sentence.
That's easy. Now, what I need is to return a the key value of the just inserted record.
Someone does know how to do this?
In you SP use:
return SCOPE_IDENTITY()
Then in C# code:
comm = new SqlCommand("InsertANewRequest", conn);
comm.CommandType = CommandType.StoredProcedure;
SqlParameter newReqNumber = new SqlParameter("@.RETURN_VALUE", SqlDbType.Int);
comm.Parameters.Add(newReqNumber);
newReqNumber.Direction = ParameterDirection.ReturnValue;
try
{
// Open the connection
conn.Open();
// Execute the command
comm.ExecuteNonQuery();
int newReq = Convert.ToInt32(newReqNumber.Value);
}
Thanks a lot!
While you posted this I solved it out using SELECT @.@.Identity
Is there any diference with the solution you gave me?
|||Quote from BOL:
|||SCOPE_IDENTITY, IDENT_CURRENT, and @.@.IDENTITY are similar functions because they return values that are inserted into identity columns.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL).
SCOPE_IDENTITY and @.@.IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @.@.IDENTITY is not limited to a specific scope.
Konstantin Kosinsky wrote:
In you SP use:
return SCOPE_IDENTITY()
Then in C# code:
comm = new SqlCommand("InsertANewRequest", conn);
comm.CommandType = CommandType.StoredProcedure;
SqlParameter newReqNumber = new SqlParameter("@.RETURN_VALUE", SqlDbType.Int);
comm.Parameters.Add(newReqNumber);
newReqNumber.Direction = ParameterDirection.ReturnValue;
try
{
// Open the connection
conn.Open();
// Execute the command
comm.ExecuteNonQuery();
int newReq = Convert.ToInt32(newReqNumber.Value);
}
No comments:
Post a Comment