Avatar of HLRosenberger
HLRosenbergerFlag for United States of America

asked on 

inserting records

I'm inserting records into a table.  I want to retrieve the primary key of the inserted record.  How can I do this?  I know I could get the max of the column that is the primary key, but another record could have been written by the time I retrieve it.
Microsoft SQL ServerMicrosoft SQL Server 2005SQL

Avatar of undefined
Last Comment
HLRosenberger
Avatar of kaminda
kaminda
Flag of Sri Lanka image

If the primary key is a Identity column you can use

@@SCOPE_IDENTITY variable to get the inserted value.
SOLUTION
Avatar of kaminda
kaminda
Flag of Sri Lanka image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
SOLUTION
Avatar of Imran Javed Zia
Imran Javed Zia
Flag of Pakistan image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of HLRosenberger
HLRosenberger
Flag of United States of America image

ASKER

Do I have to use a stored proc?  Right now I'm doing the insert like this:

Connection = New SqlConnection(ConnectionString)
        Command = New SqlCommand(SQL, Connection)
        Connection.Open()
        Command.ExecuteNonQuery()
        Connection.Close()
ASKER CERTIFIED SOLUTION
Avatar of Paul Jackson
Paul Jackson
Flag of United Kingdom of Great Britain and Northern Ireland image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of HLRosenberger
HLRosenberger
Flag of United States of America image

ASKER

Thanks!
Microsoft SQL Server
Microsoft SQL Server

Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.

171K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo