简体   繁体   中英

How to execute INSERT..SELECT statement

I want to execute ( INSERT .. SELECT ) statement like this :

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

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

    ExecuteScalar()

...which will allow a scalar value to be returned.

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