c# last insert id

2020-04-30 03:19发布

问题:

I'm using a stored procedure with this sql:

INSERT INTO [dbTblUsers]([strUsername], [strPassword])
VALUES (@p1,@p2);
SELECT @@IDENTITY;

And calling the procedure:

// Insert new user
nId = daUsers.InsertQuery(textBoxUsername.Text, textBoxPassword.Text);
// Insert new Twitter OAuth
daTwitterOAuth.Insert(nId, textBoxConsumerKey.Text, textBoxConsumerSecret.Text, textBoxToken.Text, textBoxTokenSecret.Text);

How do I cast the object @@IDENTITY int the int nId? Like this?

nId = (int)daUsers.InsertQuery(textBoxUsername.Text, textBoxPassword.Text);

回答1:

Firstly, don't use @@IDENTTY - use SCOPE_IDENTITY(); the first can give you unexpected answers if there are any triggers involved. Secondly; both of these return decimals; cast it at the call-site, IMO:

SELECT CAST(SCOPE_IDENTITY() as int)