views:

126

answers:

1

Is it possible to add multiple queries to the SqlCommand object in .net?

And if one of the queries fails and the rest succeeds, does the command report this as a failure or succes?

last question: can the queries share the same parameters? So, is this possible:

 UPDATE mytable 
    SET column1 = @param1 
  WHERE recid = @recid; 

 UPDATE mytable2 
    SET column1 = @param1 
  WHERE recid = @recid2;

(so the param1 is shared between the queries)

thanks!

R

+2  A: 

You can have multiple statements in the CommandText of a SqlCommand object, that's not a problem, and they can share parameters too. It essentially gets passed to sp_exectuesql on sql server and executed. If you're doing multiple UPDATEs then you'll want to do them inside a transaction so that you can rollback if there is a failure in one of the statements.

If returning multiple recordsets, you can use SqlDataReader's NextResult() method to get the next resultset.

Russ Cam
ok thanks... no need for a transaction for me, since I don't care if one opf them gets done if one fails...I just have to know if any of them fails... Do you know how this is handled? If anyone of them fails, am I notified?
Toad
when you say fails, do you mean a syntactical error in the sql statement? Or do you mean, as in the example statement given, if one of two UPDATE statements doesn't update any rows? The former will throw a SqlException however many statements you have, with the latter I think that you would still need to keep the statements separate in order to assess the return value of `ExecuteScalar()`/`ExecuteNonQuery()`
Russ Cam
the latter... ok... so you are saying that in that case I'd either have to separate the queries or use a transaction right?
Toad
For the latter, as far as the database is concerned, an UPDATE affecting no rows is not an error. It may be an error for your application logic however. There are a couple of ways to handle this that I can think of off the top of my head, which may involve a transaction depending on whether the statements are all or nothing. You could use a return value or use RAISERROR to return a message to the calling application.
Russ Cam
ok thanks for all the help!
Toad