tags:

views:

49

answers:

2

I am using SQL Server 2005 and c#. I want to get primary key value when I insert record into database.

For this I have a C# method in which I insert and update records. I am using ExecuteScalar method for inserting and updating.

Insert record is successful but when I edit record then no update is successful.

So tell me can I use ExecuteScalar method for update and insert record and HOW

+2  A: 

Generally, ExecuteScalar method is used for queries which return at least one field of data (e.g. result from SELECT query). If you just want something to be executed, you should use ExecuteNonQuery method instead.

Even with ExecuteNonQuery method you could still read values of parameters after function completed. For example, your command could be something like:

INSERT INTO TableName(someFields) VALUES (someValues)
SET @Id = SCOPE_IDENTITY()

if you're using autoincrement key or

SET @Id = newid()
INSERT INTO (ID, someFields) VALUES (@id, someValues)

if you're using uniqueidentifier as a key.

After that you could add output @Id parameter to the command, call ExecuteNonQuery and after that read the value from parameter.

Ivan Ferić
SELECT_IDENTITY probably wants to be scope_identity(), and using newid() for an ID field is *probably* a bad thing - because it's fairly likely that that ID field is a clustered PK, and using newID() as a clustered index causes heavy fragmentation, guaranteed. newSequentialID() is a better choice.
Matt Whitfield
Yeah, I mistyped it, it's scope_identity(), fixed it. NewSequentialId() could be a good idea too.
Ivan Ferić
A: 

With ExecuteScalar, you should be able to execute any query (including insert/update) although, it makes more sense to use ExecuteNonQuery for update operation as generally, you don't expect any result. What happens when you do Update operation? Do you get any exception or the record simply does not get updated? If former then share the exception details. If later (i.e. record does not get updated) then check the value of primary id field that you are passing (I believe via some parameter). If its null or zero the no record will be updated.

VinayC