简体   繁体   English

如何执行INSERT..SELECT语句

[英]How to execute INSERT..SELECT statement

I want to execute ( INSERT .. SELECT ) statement like this : 我想执行这样的( INSERT .. SELECT )语句:

cmdTxt.Clear();
cmdTxt.Append(" INSERT INTO  aast:sc1pen ");
cmdTxt.Append(" SELECT action_month,action_year,200,emp_num,penalty_action , ");
cmdTxt.Append("  'APPLY ' || penalty_reason || ' day ' , 0 , 0 ");
cmdTxt.Append(" FROM sc2pen WHERE sal_year = ? and sal_month = ? and penalty_type = 1 and pay_type = 0 ");
myIfxCmd.CommandText = cmdTxt.ToString();

myIfxCmd.Parameters.Clear();

myIfxCmd.Parameters.Add("sal_year", IfxType.Integer);
myIfxCmd.Parameters.Add("sal_month", IfxType.Integer);

myIfxCmd.Parameters[0].Value = penaltyDt.Rows[0]["sal_year"];
myIfxCmd.Parameters[1].Value = penaltyDt.Rows[0]["sal_month"];

Now I'm confused should i use 现在我很困惑我应该使用

myIfxCmd.ExecuteNonQuery(); 

To execute query like this although it include read operation ? 要执行这样的查询,尽管它包含读取操作?

Firstly, it is not a good idea to do inline SQL as this does not make for maintainable code. 首先,执行内联SQL并不是一个好主意,因为这不能维护代码。 This should be done in the database inside a stored procedure ideally - especially for inserting data into an existing table. 理想情况下,应该在数据库中的存储过程中完成此操作-尤其是将数据插入现有表中时。 Then you can execute the SP and return data inside an output parameter. 然后,您可以执行SP并在输出参数中返回数据。

However, if you really want to go down this route then executing 但是,如果您真的想走这条路,请执行

    ExecuteNonQuery()

...will not return any data, only the records affected. ...将不返回任何数据,仅影响记录。 If you want to return some data, like the id of the newly inserted record, you want to use 如果要返回一些数据,例如新插入的记录的ID,则要使用

    ExecuteScalar()

...which will allow a scalar value to be returned. ...这将允许返回标量值。

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

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