我经常需要为SQL Server Management Studio上的存储过程“生成脚本”。我需要创建一个WPF应用程序来获取生成的文件并执行它。我知道你可以这样做:
SqlCommand insert = new SqlCommand(sql, conn);
insert.ExecuteNonQuery();
如果我将整个脚本文件文本传递给sql,这会执行所有操作吗?
答案 0 :(得分: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();
}