在C#中运行SQL脚本到某个数据库或表?

时间:2015-07-24 07:13:28

标签: c# sql database

如何在C#中将SQL脚本运行到某个数据库或表? 这是我目前的设置:     我有一个内置多个数据库的服务器。我想在某个数据库或表上运行SQL脚本,如何在C#中运行脚本,其中我可以定义脚本应该在哪个数据库/表中运行?感谢

3 个答案:

答案 0 :(得分:0)

只是众多方法中的一种,而不是最干净的方法:当您创建SqlCommand时,直接在其构造函数中设置ConnectionString。

SqlCommand Class

SqlConnection Class (your ConnectionString)

答案 1 :(得分:0)

您可以尝试USE声明。也就是说,在运行sql脚本之前尝试使用数据库名称,例如

USE DatabaseName;
SELECT * FROM TableName;

否则,您也可以尝试在表名中关联数据库名称,如

SELECT * FROM DatabaseName.TableName;

希望这会有所帮助......

答案 2 :(得分:0)

要从C#运行脚本,你应该像这样对脚本。在这里,您将数据库名称定义为“初始目录”。

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);
    }
}

之后你的sql脚本文件应该管理需求。比如你需要在查询中使用哪个表,你也可以使用'。'连接其他数据库的表。运算符语法是这样的。

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