简体   繁体   English

通过ADO.NET命令对象执行的多条SQL语句

[英]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. 下面是一条SQL语句,它通过首先尝试更新记录来实现我的目标,如果不存在,它将执行插入操作。 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. 我想知道它是否可以通过ADO.NET命令对象直接执行,还是需要进入存储过程。

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 T-SQL中的MERGE命令仅适用于这种情况

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. 使用MERGE您可以开始定义TARGET表(T),然后使用包含TARGET中主键字段值的参数构建一个名为SOURCE (S)的伪表。 Now the two tables are JOINED ON the field CustomerNumber . 现在,这两个表已JOINED ONCustomerNumber字段上。 The product of this join could be MATCHED or NOT MATCHED depending of the previous presence of the record in the TARGET table. 取决于TARGET表中记录的先前存在情况,此NOT MATCHED可以是MATCHEDNOT MATCHED 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) 查询的其余部分可能是不言自明的,只是请注意,在两个操作(UPDATE和INSERT)中,无需重复MyTable名称(它是TARGET)

By the way, yes you could pass multiple commands to the SqlCommand separated by a semicolon 顺便说一句,是的,您可以将多个命令传递给以分号分隔的SqlCommand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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