I have a winforms app that includes the following class method:
public aSqlQuery(SqlCommand pSqlCom, string pMode = "object", bool pGetID = false)
{
try
{
string strConnection = aSystem.ConnectionString;
SqlConnection linkToDB = new SqlConnection(strConnection);
pSqlCom.Connection = linkToDB;
switch (pMode)
{
case "non query":
{
linkToDB.Open();
pSqlCom.ExecuteNonQuery();
if (pGetID == true)
{
SqlCommand sqlCom = new SqlCommand("SELECT @@IDENTITY;", linkToDB);
this.LastID = (int)sqlCom.ExecuteScalar();
}
linkToDB.Close();
}
break;
plus other switches
The pSqlCom (SqlCommand) executes fine becuase I can see the data written into the database. However the subsequent “SELECT @@IDENTITY” statement gives an invalid cast error
What am I doing wrong and how can I retrieve the new ID created by SQL within my class method?
The correct answer it turns out was that the SELECT SCOPE_IDENTITY() statement had to form part of the same SqlCommand as the INSERT statement which preceeded it, but which I had contained in the previous SqlCommand ‘pSqlCom’. Once the SELECT SCOPE_IDENTITY() was incuded as part of pSqlCom the code correctly returned the Identity.