简体   繁体   中英

Can I use ExecuteScalar for updates?

I am using SQL Server 2005 and C#. I want to get the primary key value when I insert records into the database.

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

Inserting is successful, but updates are not. How can I use ExecuteScalar to get the primary key for updates as well?

Generally, ExecuteScalar method is used for queries which return at least one field of data (eg 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.

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM