Kluong Kluong - 1 year ago 96
ASP.NET (C#) Question

Insert Data into SQL DB and Select PK and Store it into a session in ASP.NET C#

Is there a way to select the value of the PK of the inserted data into sql DB and then store it into a session on ASP.NET C#?

For example: I've insert something into the database. During that insert, I want to return that PK back to me and store it into a session.

Answer Source

Agree this is a somewhat vague question, but hopefully this will help.

Assuming this is SQL Server, you could use scope_identity(). Use a stored procedure to insert the row, and read back the value

e.g. assuming this table

create table Foo(FooId int identity(1,1) primary key, Field varchar(50))

create a procedure

create procedure dbo.usp_FooInsert 
    @fieldValue varchar(50)

insert into Foo(field) values(@fieldValue)

select SCOPE_IDENTITY() as InsertedFooId

Use the procedure in place of your current insert statement and read back the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download