Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i run sql server script with c#?

Tags:

c#

sql-server

I'm write this code for run sql server script:

string sqlConnectionString = "Data Source=.;Initial Catalog=behzad;Integrated Security=True";
//string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("d:\\behzadBULK.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);


but this line :

Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));

i get this error:

 Are you missing reference?


what reference should be add to the project?

like image 527
behzad razzaqi Avatar asked May 23 '15 05:05

behzad razzaqi


People also ask

Can you use SQL with C?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

How do I run a SQL Server script?

Click Query > Connection > Connect to connect to the server that contains the database you want to access. Select the appropriate StarTeam Server database. Open the tuning script, by choosing File > Open > foldername\scriptname. Execute the script, by clicking the Execute button on the toolbar or by pressing F5.

Can we write C# code in SQL Server?

Various Programming Languages like C# and . Net are compatible with Oracle and Microsoft SQL Server. Also, they follow the same logic with each database in most cases. Here are a few concepts common for all Databases.

How do I run a query in C#?

To execute your command directly from within C#, you would use the SqlCommand class.


1 Answers

Your problem here is that a reference to the assembly Microsoft.SqlServer.Server is missing and that's why that error is popping up.

You can resolve it by just adding a reference to your project for that particular assembly by right clicking your project and clicking on add reference. That should open a window to show you all the assemblies available and from there you can choose this assembly and add it to your project.

After that, make sure you have added the namespace for it in your code and that should do it.

Hope this helps.

like image 50
Matt Murdock Avatar answered Oct 06 '22 04:10

Matt Murdock