0

我经常需要为 SQL Server Management Studio 上的存储过程“生成脚本”。我需要创建一个 WPF 应用程序来获取生成的文件并执行它。我知道你可以这样做:

SqlCommand insert = new SqlCommand(sql, conn);
insert.ExecuteNonQuery();

如果我将整个脚本文件文本传递给 sql,这会执行所有操作吗?

4

1 回答 1

2

看看这个:How to execute an .SQL script file using c#

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

[...]

private void Execute(object sender, EventArgs e)
{
    string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";

    FileInfo file = new FileInfo(@"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");

    string script = file.OpenText().ReadToEnd();

    SqlConnection conn = new SqlConnection(sqlConnectionString);

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

    server.ConnectionContext.ExecuteNonQuery(script);
    file.OpenText().Close();    
}
于 2012-10-02T12:39:11.437 回答