c#


C#/SQL get autoincremented field value


I have a table with autoincremented primary key. In my code I am trying to receive the new autoincremented value when I execute each 'insert' query. Is there a way to do it programatically?
Thanks.
UPD:
Assume I have a table:
TABLE User ( userID INT NOT NULL AUTO_INCREMENT, name VARCHAR( 25 ) NOT NULL , email VARCHAR( 50 ) NOT NULL , UNIQUE ( userID ) );
And I when I insert new values (name and email) to this table I want automatically receive newly generated userID. Ideally I am looking for any ways to do that with a single transaction and without stored procedures.
Have your sql/stored proc return scope_identity() or if you are using Linq2SQL or EF the entity used for insertion gets the new id.
In the stored proc it is:
ALTER proc [dbo].[SaveBuild](
#ID int = 0 output,
#Name varchar(150)=null,
#StageID int,
#Status char(1)=null
)
as
SET NOCOUNT ON
Insert into Builds
(name, StageID, status)
values (#Name, #StageID, #Status)
select #ID = scope_identity()
RETURN #ID
In the C# code you have:
public int SaveBuild(ref int id, ref string Name)
{
SqlCommand cmd = GetNewCmd("dbo.SaveBuild");
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = id;
cmd.Parameters["#ID"].Direction = ParameterDirection.InputOutput;
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
cmd.Parameters.Add("#StageID", SqlDbType.Int).Value = 0;
ExecuteNonQuery(cmd);
id = (int)cmd.Parameters["#ID"].Value;
return id;
}
Dependent upon your situation, you might be better off using table-valued parameters to pass your inserts to a stored procedure, then use OUTPUT INSERTED to return a table-valued parameter from your stored procedure.
It will drastically reduce the number of hits required if you're processing multiple items.
Are you limited to building SQL on the client and sending it to the server? Cause if you can use a stored procedure, this is easy to do. In the stored proc, do the insert and then, either
Select Scope_Identity() as the last statement in the stored proc., or
Use a output parameter to the stored proc, (say named #NewPKValue) and make the last statement:
Set #NewPKValue = Scope_Identity()
Otherwise, you need to send a batch of commands to the server that include two statements, the insert, and Select Scope_Identity() and execute the batch as though it was a select statement
You could use the SQL statement SELECT scope_identity().

Related Links

C# how to specify SetupDiGetDeviceRegistryProperty field value SPDRP_HARDWAREID
Where do these extra characters come from from a user's profile name?
C# asynch SQL inside singleton and delegates
'Throwing warnings' from my code
List.Count resets to zero
HtttpWebRequest returns result of a request in another thread (Monotouch)
XNA game items drag and drop — how to implement object exchange?
html routing helpers are making a call against a storing data
WebClient download many files error — Invalid URI: The URI is empty
Move image inside image-element
move to the end of the text in textbox
Sharepoint Workflow Global Variables in C# Workflow Project
Maintain HTML encoding when processing RSS XML via XSLT
How to force a listbox to always have at least one item selected and highlighted?
Locking VSS progammatically
Allow null value when parsing file to datatable

Categories

HOME
excel-formula
ssms
ftp
customization
cxf
azure-eventhub
azure-resource-manager
mediarecorder
uml-designer
cdn
obd-ii
soap-client
dcos
decoding
ng2-charts
opendaylight
infopath
web-worker
dompdf
brightway
smooth-scrolling
accordion
minimagick
xna
infinite-loop
email-client
stack-trace
mex
checkmarx
meteor-accounts
jmsserializerbundle
postgresql-9.6
openvms
n1ql
machine-code
odp.net
wit-ai
sampling
dotnetnuke-module
lfe
ninja-forms
ssdp
wicket-tester
android-graphview
java-5
firefox-developer-edition
nao-robot
lucee
skype-bots
strtol
symantec
jspx
konakart
git-cherry-pick
ooad
edgar
adempiere
exchange-server-2007
joomla3.3
nmock
clearquest
avd
pymol
data-quality-services
jad
dockerpy
apache-pivot
go-gin
breeze-sharp
nsnotificationcenter
nest-initiative
disabled-control
msdropdown
visual-c#-express-2010
rails-migrations
android-relativelayout
new-operator
logo-lang
grunt-contrib-imagemin
kendo-window
oc4j
azure-pack
select2-rails
coinbase-php
nx
brew
database-restore
antixsslibrary
invalidoperationexception
netzke
xcode4.6.3
certificate-revocation
event-propagation
google-email-audit-api
parsec
eeprom
towerjs
execjs
cpack
s60
nyromodal
nstoolbar
qprocess

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App