I know there is a class system.data.sqlclient.sqlcommand that can execute a batch at a time. Since I have a lot if SQL Server scripts (in which there is some GO key words in it), I need to find a way that can throw this script to SQL Server for executing. How to do this ? Thanks.
Edit:
Hi Enrico, thanks for the information you provided. The executenonquery method will return a int[] type. How can I get all the text result? For example, I have this SQL script called sql.sql.
PRINT 'blah blah blah';
GO
SELECT @@SERVERNAME AS instance;
When I use sqlcmd to execute it, I get the following result.
C:\TEMP>sqlcmd -S (local)\instance1 -U a -P a -i sql.sql
blah blah blah
instance
-------------------------------------------------------------------
THESIMPSONS\INSTANCE1
(1 rows affected)
C:\TEMP>
How can I get the similar result using SMO or ADO.NET classes? Thanks.
The ServerConnection.ExecuteNonQuery method part of the SQL Server Management Objects (SMO) API will correctly execute T-SQL scripts that contain multiple batches separated by the
GOkeyword.As a side note, you can even decide to use your own batch separator by setting the ServerConnection.BatchSeparator property, which by default is
"GO".If your script returns multiple result sets that you wish to get back in your application, you can use either the ServerConnection.ExecuteReader or the ServerConnection.ExecuteWithResults method. However, keep in mind that those methods do not support T-SQL scripts with multiple batches. At this point you have a couple of options:
"GO"separator into multiple strings, each containing a single batch, and execute them through one of the methods mentioned above.SQLCMDfrom your code by spawning a new process and passing the script to execute as a parameter.