4

I have a populated SqlCommand object containing the command text and parameters of various database types along with their values. What I need is a T-SQL script that I could simply execute that would have the same effect as calling the ExecuteNonQuery method on the command object.

Is there an easy way to do such "script dump" or do I have to manually construct such script from the command object ?

1
  • To my knowledge there is not such function, im afraid you're gonna have to write something like this yourself by passing the SqlCommand object into a (static) method. Commented Mar 30, 2010 at 8:55

1 Answer 1

4

I don't think you can get the complete sql statement from the SqlCommand object directly. If you log all commands sent to your sql server you will see that the command text that is passed is the same as the command text of your SqlCommand object. The parameter values are passed separately.

So I think that your only option will be to build the command text yourself. This is quite easy really; You start with the CommandText of the SqlCommand and iterate through the Parameters collection replacing the parameter place holders with (escaped) parameter values. This should result in a complete sql query that does what you are after.

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

3 Comments

That sounds fine, but is there an easy way to escape these values ?
+1. Used this approach for logging SQL exceptions out to include a "TSQL script" dump ready to copy and paste to try manually/debug in SSMS
If you are passing complex types like blobs or xml data then escaping them will be hard. But assuming you are passing simple values like varchars and numbers it should be as simple as enclosing the values in apostrophes (') and replacing any contained apostrophes with doulbe ones (replace ' with ''). One thing to look out for is dates. They must be formatted properly, but I don't remember the excact format right now.

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.