简体   繁体   中英

Run an SQL script to a certain Database or Table in C#?

How do I run an SQL script to a certain Database or Table in C#? This is my current setup: I have a server with multiple databases inside. I want to run an SQL script on a certain Database or Table, How do I run the script in C# wherein I could define in which database/table the script should run? Thanks

Just one of many ways, not the cleanest: When you create your SqlCommand set the ConnectionString directly in its constructor.

SqlCommand Class

SqlConnection Class (your ConnectionString)

You can try USE statement. That is, try using the database name before running the sql script something like,

USE DatabaseName;
SELECT * FROM TableName;

Otherwise you could also try associating the database name in the tablename like,

SELECT * FROM DatabaseName.TableName;

Hope this helps...

To run script from C# you should right the script like this. Here you are defining the database name as 'Initial Catalog'.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;

public partial class ExcuteScript : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    string sqlConnectionString = @"Initial Catalog=northwind;Data Source=subhash\SQLEXPRESS;Integrated Security=SSPI;Persist Security Info=False;";

    string script = File.ReadAllText(@"E:\Project Docs\TACT\northwinddata.sql");

    SqlConnection conn = new SqlConnection(sqlConnectionString);

    Server server = new Server(new ServerConnection(conn));

    server.ConnectionContext.ExecuteNonQuery(script);
    }
}

After that your sql script file should manage the requirements.like which table you need to use in your query and you can also connect the tables of other databases using '.' operator syntax is like this.

 select * from [database].[schema].[table]  where <condition>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM