Wednesday, March 7, 2012

getting key just entered

************* Edited by moderator Adec ***************
Inserted missing < code></ code> tags (without the
spaces inside). Always include such tags when
including code in your postings. Don't force the
moderators to do this for you. Many readers disregard
postings without the code tags.
**************************************************

Hi

Probably a dumb question but I'm doing an insert into a table with an identity field. How do I get the key back straight after I add it?

This is how I do the addition


SQLString = "Insert into users (username,password,status,campus, ulevel ) values ( @.username, @.password, @.status, @.campus, @.ulevel)"
cmdInsert = new SQLCommand(SQLString, conn)
cmdInsert.Parameters.Add( "@.username", _username)
cmdInsert.Parameters.Add( "@.password", md5Hasher.ComputeHash(encoder.GetBytes(_password)))
cmdInsert.Parameters.Add( "@.status", _status)
cmdInsert.Parameters.Add( "@.campus", _campus)
cmdInsert.Parameters.Add( "@.ulevel", _ulevel )
conn.Open()
cmdInsert.ExecuteNonQuery()
conn.close()

but about now I need the primary key just generated.
Any ideas?

Thanks
ABoldWhat database do you use.|||If you are using SQL server, you can return the value of @.@.identity after the insert.|||I wouldnt use @.@.identity. When you are insert into a table that has a trigger and creates another identity value then you will get the last value generated in any table. Use instead SCOPE_IDENTITY(). It will return the generated value for the current scope.

Morehere...|||Like I said, first we need to know which Db the Poster is using. Then we can decide which way to go. SCOPE_IDENTITY() is only available in SQL 2000 Server and later.|||Yes I'm using SQL Server 2000.

SO I can use SCOPE_IDENTITY() thanks I'll look it up.

Thanks
ABold

No comments:

Post a Comment