02 August, 2011

Get Identity Column Value of SQL Server using C#

For getting the identity column value ,please do the following :-

  1. Let table name is tblInfo and column name is colID and colName, where colID is auto generated (pk). you need to get current colID value after data insert.
  2. let write insert command INSERT INTO tblInfo(colName) VALUES('imran');
  3. Add this SELECT SCOPE_IDENTITY();
  4. so its looks like : INSERT INTO tblInfo(colName) VALUES('imran');

    SELECT SCOPE_IDENTITY();
  5. then in C# :
long returnID=0;

object objRet=null;

string _SQL="INSERT INTO tblInfo(colName) VALUES('imran');

SELECT SCOPE_IDENTITY();";

_sqlCommand=new SqlCommand(_SQL,_sqlConnection);

objRet=_sqlCommand.ExecuteScalar();

returnID=Convert.ToInt32(objRet.ToString());

Then you can get inserted ID value in returnID.

No comments:

Post a Comment