Showing posts with label catch. Show all posts
Showing posts with label catch. Show all posts

Wednesday, March 7, 2012

Inserting values and get the last ID recorded to use in another INSERT

I need to insert some values into a table and after that catch the ID inserted.

I set some input parameters in stored procedure and only one to get the @.id defined as output

SqlParameter paramIdPedido = new SqlParameter("@.APP_IDPEDIDO", SqlDbType.Int, 4);
paramIdPedido.Direction = ParameterDirection.Output;
cmd.Parameters.Add(paramIdPedido);

Do I have to run cmd.ExecuteNonQuery(); to record first what I need and after
run ExecuteReader: something like SqlDataReader dr = cmd.ExecuteReader();while (dr.Read()... to get the ID)

From stored procedure:

INSERT table(fields) VALUES(vars)
SELECT TOP 1 @.id = id FROM table ORDER BY id DESC

I must do all these steps or maybe is there anything less complex to do?

Thanks!

Hello Roberot,

Have a look at the following example:http://davidhayden.com/blog/dave/archive/2006/02/16/2803.aspx

Jeroen Molenaar.