简体   繁体   中英

Multi SQL statements executed via ADO.NET command object

I need to update a record in a table but it is possible that the record does not exist, so I would need to insert the record.

Below is a SQL statement that accomplished my goal by trying to update the record first and if it doesn't exist it performs an insert. What I am wondering if it can be executed directly via ADO.NET command object or does it need to go into a stored procedure.

UPDATE MyTable SET ReservationDate = @ReservationDate WHERE CustomerNumber = XXXX;
IF @@ROWCOUNT=0
  INSERT INTO MyTable (CustomerNumber , ReservationDate) 
  VALUES (@CustomerNumber , @ReservationDate)

If I could execute it via the command object without a stored procedure it would mean one less dependency for deployment time (ie deploying the stored procedure).

The MERGE command in T-SQL works for just this scenario

string cmdText = @"MERGE MyTable T
                   USING (SELECT @CustomerNumber As CustomerNumber) as S 
                   ON T.CustomerNumber = S.CustomerNumber
                   WHEN MATCHED UPDATE SET ReservationDate = @ReservationDate 
                   WHEN NOT MATCHED INSERT INTO (CustomerNumber , ReservationDate)  
                                    VALUES (@CustomerNumber , @ReservationDate)";

It is just one string of text wrapped for readability in more lines thanks to the verbatim character @

With MERGE you start defining your TARGET table (T), then you build a pseudotable called SOURCE (S) with the parameter that contains the value for the primary key field in TARGET. Now the two tables are JOINED ON the field CustomerNumber . The product of this join could be MATCHED or NOT MATCHED depending of the previous presence of the record in the TARGET table. The remainder of the query is probably self explanatory, just notice that in the two actions (UPDATE and INSERT) there is no need to repeat the MyTable name (it is the TARGET)

By the way, yes you could pass multiple commands to the SqlCommand separated by a semicolon

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