Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

How to execute sql script from C# Expand / Collapse
Author
Message
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);
}

file.OpenText().Close();
}


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


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 2:02 PM
Points: 13,539, Visits: 11,342
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 LessThanDot.

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


SSChampion

SSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampionSSChampion

Group: General Forum Members
Last Login: Today @ 2:39 PM
Points: 12,923, Visits: 32,313
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.


Lowell

--There is no spoon, and there's no default ORDER BY in sql server either.
Actually, Common Sense is so rare, it should be considered a Superpower. --my son
Post #1599216
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse