Question: I'm working on an ASP.NET project (C#) with SQL Server 2008.

When I insert a row into a table in the database, I would like to get the last inserted ID, which is the table's **IDENTITY** (Auto Incremented).

I do not wish to use another query, and do something like...

```
SELECT MAX(ID) FROM USERS;

```

Because - even though it's only one query - it feels lame...

When I insert something I usually use **ExecuteNonQuery()**, which returns the number of affected rows.

```
int y = Command.ExecuteNonQuery();

```

Isn't there a way to return the **last inserted ID** without using another query?

Answer: 
You can return the id as an output parameter from the stored procedure, e.g. `@userId int output`

Then, after the insert, `SET @userId = scope_identity()`
> 
> * even though it's only one query - it feels lame...
> 
> 
> 

It actually is also wrong as you can have multiple overlapping iserts.

That is one thing that I always fuind funny - people not reading the documentation.

```
SELECT SCOPE_IDENTITY()

```

returns the last identity value generated in a specific scope and is syntactically correct. It also is properly documented.

> 
> Isn't there a way to return the last inserted ID without using another query?
> 
> 
> 

Yes. Ask for the number in the saame SQL batch.

```
INSERT (blablab9a); SELECT SCOPE_IDENTITY ();

```

as ONE string. ExecuteScalar.

You can have more than one SQL statement in one batch.