Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
.NET and @@identity
Message
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Divers
Thread ID:
00666202
Message ID:
00666486
Vues:
20
Interesting. I was not able to return the new IDENTITY value by making two queries on the same connection. I kept getting a System.DBNull. But I was able to get the following to work correctly.
static void Main(string[] args)
{
	SqlConnection cn = new SqlConnection(connString);
	SqlCommand cm = new SqlCommand();
	Int32 newID = 0;
	Object o;

	cm.Connection = cn;
	cm.CommandType = CommandType.Text;
	cm.CommandText = "INSERT INTO miketest VALUES (1); SELECT SCOPE_IDENTITY()";

	cn.Open();
	newID = Convert.ToInt32(cm.ExecuteScalar());

	cn.Close();

	Console.WriteLine("New ID: {0}", newID);

}
The test table looks like this:
CREATE TABLE miketest (
	pk int identity(1,1)
	,c int)
IMO, calling a stored procedure to do the insert and then return the new IDENTITY value is the better approach.

-Mike
Michael Levy
MCSD, MCDBA
ma_levy@hotmail.com
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform