Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

How to execute sql script from C# Expand / Collapse
Posted Monday, August 4, 2014 12:38 AM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Wednesday, August 20, 2014 8:06 AM
Points: 55, Visits: 336
Hi Guys,

I have this code to execute a sql script in C#. It works great but I'm not happy with the dependency on the following. If the PC I want to run this on has no SQL Server installed this will fail. I need a better way. It needs to work for scripts that have GO statements in them as well.

using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

 if (File.Exists(filePath))
FileInfo file = new FileInfo(filePath);
string script = file.OpenText().ReadToEnd();

using (SqlConnection conn = new SqlConnection(connectionString))

Server server = new Server(new ServerConnection(conn));
ReturnValue = server.ConnectionContext.ExecuteNonQuery(script);


Post #1599123
Posted Monday, August 4, 2014 12:54 AM



Group: General Forum Members
Last Login: Today @ 6:23 AM
Points: 15,499, Visits: 13,162
Do you really need to install the entire SQL Server? I think the SQL client alone is probably enough.

The GO statement is not a T-SQL statement, but a batch seperator for SSMS and SQLCMD.
It will not work outside those environments.

How to post forum questions.
Need an answer? No, you need a question.
What’s the deal with Excel & SSIS?

Member of LinkedIn. My blog at SQLKover.

MCSA SQL Server 2012 - MCSE Business Intelligence
Post #1599125
Posted Monday, August 4, 2014 6:03 AM



Group: General Forum Members
Last Login: Today @ 2:39 PM
Points: 14,540, Visits: 38,379
you can explicitly extract both those DLLs from the GAC(Global Assembly Cache), and then make sure they are in your bin folder with the executable you are calling.
in that way, your references are available, without having to install SQL on the machine it is executed from.

the problem, of course, is you need someone to select the target server with the appropriate permissions., and split the document up into multiple separate commands based on the GO statement, and execute each of those commands in a loop.


help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!
Post #1599216
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse