4

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
  • 1
    You really want a transaction for that. Commented Oct 1, 2009 at 13:04
  • there is no need for it to be atomic or transactional. I just want to perform a set of operations. I just want to be sure everyone of them got done Commented Oct 1, 2009 at 13:10

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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()
the latter... ok... so you are saying that in that case I'd either have to separate the queries or use a transaction right?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.