Click here to Skip to main content
15,896,372 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, i am using the 3 tier architecture for my project. I am trying to retrieve the last inserted value into my database table using the SCOPE_IDENTITY.

Any idea how i can achieve this using SCOPE_IDENTITY AND the 3 tier architecture?
Posted
Comments
Rob Philpott 17-Jun-13 11:37am    
Please be more specific. Are you trying to do this from C# or in a stored proc. Basically you just select SCOPE_IDENTITY() and use something like ExecuteScalar to get that, but you need to make sure the scope is correct. Ideally do it in a stored proc and call from c#..
Jerrell77 17-Jun-13 12:00pm    
Hi Sorry for being unclear. I'm trying to use SCOPE_IDENTITY() using SQL Cmd in the DAL as such :

public int getScope()
{
SqlConnection conn;
StringBuilder sql;
SqlCommand sqlCmd;
int result;

result = 0;
conn = dbConn.GetConnection();
sql = new StringBuilder();
sql.AppendLine("SELECT SCOPE_IDENTITY() FROM WP_advUploads");


try
{
conn.Open();
sqlCmd = new SqlCommand(sql.ToString(), conn);
result = Convert.ToInt32(sqlCmd.ExecuteScalar());


}
catch (Exception ex)
{
errMsg = ex.Message;
}
finally
{
conn.Close();
}
return result;
}

The Error Message was "Invalid column SCOPE_IDENTITY()"

1 solution

Unfortunately, you can't use Scope_Identity() like in your reply to Rob's comment above.

You should only call Scope_Identity() immediately after you've done an INSERT into a table that has an IDENTITY column - since its purpose is to get the identity value generated by the database engine for the inserted row.

As Rob says, doing it in a stored procedure is often the best way. If you use a stored procedure, you could do something like this:
C#
sqlCmd.CommandText = "sp_InsertIntoUploads";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue(...);
.... for all values to store
sqlCmd.Parameters.AddWithValue("@Id", 0).Direction = ParameterDirection.Output;

var id = sqlCmd.ExecuteNonQuery();

And your stored procedure would look like this:
SQL
CREATE PROCEDURE dbo.sp_InsertIntoUploads
(
... values to put into the columns...,
@Id INT OUTPUT  -- returns the generated id
)
AS
BEGIN

INSERT INTO uploadsTable(columns...)
VALUES (values...)

SELECT @Id = Scope_Identity()

END
GO

If you prefer not to use OUTPUT parameters from the stored procedure you can use ExecuteScalar() and in the sproc use SELECT Scope_Identity().
 
Share this answer
 
Comments
Rob Philpott 17-Jun-13 13:42pm    
Sounds good! I suspect that if you do an insert and then get the identity using two commands in the same SqlCommand that will work as they are treated as a batch, but it's not something I'd do...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900