views:

105

answers:

4

I am adding data to my database, but would like to retrieve the UnitID that is Auto generated.

using (SqlConnection connect = new SqlConnection(connections)) 
{ 
SqlCommand command = new SqlCommand("ContactInfo_Add", connect); 
command.Parameters.Add(new SqlParameter("name", name)); 
command.Parameters.Add(new SqlParameter("address", address)); 
command.Parameters.Add(new SqlParameter("Product", name)); 
command.Parameters.Add(new SqlParameter("Quantity", address)); 
command.Parameters.Add(new SqlParameter("DueDate", city)); 
connect.Open(); 
command.ExecuteNonQuery(); 
} 

...

ALTER PROCEDURE [dbo].[Contact_Add] 
@name varchar(40), 
@address varchar(60), 
@Product varchar(40), 
@Quantity varchar(5), 
@DueDate datetime 
AS  
BEGIN 
 SET NOCOUNT ON; 

 INSERT INTO DBO.PERSON 
 (Name, Address) VALUES (@name, @address) 
 INSERT INTO DBO.PRODUCT_DATA 
 (PersonID, Product, Quantity, DueDate) VALUES (@Product, @Quantity, @DueDate) 
END 
+3  A: 

With MSSQL its safer to use:

SET @AN_INT_OUTPUT_PARAM = SCOPE_IDENTITY()

Or simply

RETURN SCOPE_IDENTITY() 
Alex K.
+7  A: 

Add an output parameter to your procedure:

@new_id int output

and after the insert statement, assign it value:

set @new_id = scope_identity()

The add it to your calling code:

command.Parameters.Add("@new_id", SqlDbType.Int).Direction = ParameterDirection.Output;

and retrieve the value:

int newId = Convert.ToInt32(command.Parameters["@new_id"].Value);
Ray
Typed it out before I could!
mattdell
Me too :) Blast
CResults
Racing for rep points on SO has done more for my typing skills than (many) years of previous practice :)
Ray
sorry - error in my code - should be Convert.ToInt32(command.Parameters["@new_id"].Value); - answer edited
Ray
+2  A: 

in the Stored procedure Add in the end

SELECT SCOPE_IDENTITY();

in the C# define an integer outside using and assign it inside using

int UnitID;

UnitID = command.ExecuteScalar();  
Kronass
if you're using SQL, I think you dont even need to create a new output parameter...just doing a SELECT SCOPE_IDENTITY() at the end of the sproc, and whatever you get from ExecuteScalar() in ADO.NET will be the new identity.
silverCORE
A: 

Search Books Online for OUTPUT clause if you have SQL server 2008. This is the best method.

HLGEM