Andrew Werber
asked on
Running a text file as if it was being run in SQL Server Management Studio.
Let's say you have the following text file with the next 2 lines:
Drop Table Test
GO
Using C#, how would you 'run' this file on SQL Server?
I think SQL Server is version 2012. SSMS is version 17.2. I'm using VIsual Studio 2015.
Drop Table Test
GO
Using C#, how would you 'run' this file on SQL Server?
I think SQL Server is version 2012. SSMS is version 17.2. I'm using VIsual Studio 2015.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Looking good. But one question back, why do I get an error after a GO? In the past, I would make scripts where a GO is needed.
You don't need the GO statement if you're running this in your program. You'd do something like this:
YourCommandObject.SQL = "DROP TABLE YourTable"
YourCommandObject.ExecuteN onquery
That should drop the table, assuming you have permissions to do so as Pawan mentioned.
YourCommandObject.SQL = "DROP TABLE YourTable"
YourCommandObject.ExecuteN
That should drop the table, assuming you have permissions to do so as Pawan mentioned.
Some additional info on "GO": this is not part of the T-SQL language, it's just a command that Microsoft has implemented in its SQL Server toolset. That explains the error behaviour in C#.
Ref. SQL Server Utilities Statements - GO
Ref. SQL Server Utilities Statements - GO
ASKER
Thanks. Since the original question did not ask about the GO, I'm assigning all points to this answer.
ASKER
PS, there is a way to run scripts with GO statements
tionInfo and Microsoft.SqlServer.Smo.
I also had to add the following to my CONFIG file:
var connectionString = "connection string";
var pathToScriptFile = fileToExec;
var sqlScript = File.ReadAllText(pathToScriptFile);
using (var connection = new SqlConnection(connectionString))
{
var server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(sqlScript);
}
You have to add references to Microsoft.SqlServer.ConnecI also had to add the following to my CONFIG file:
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
<requiredRuntime version="v4.0.20506" />
</startup>
ASKER
I want to say that SQLCMD as an answer to this question will not be accepted as I just found that.
I need this because my boss wants it and he determines how much I get paid. :)