【问题标题】:WPF App run SQL Server ScriptsWPF 应用程序运行 SQL Server 脚本
【发布时间】:2012-10-02 12:36:06
【问题描述】:

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

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

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

【问题讨论】:

  • 为什么你期望它执行的比你传递给它的 Sql 少?
  • 当我使用上述内容时,它一直在执行存储过程,而不是 CREATE、DROP 等。我认为它将运行整个脚本,但直到我有机会测试我想要知道 SqlCommand 是否会运行任何东西。

标签: c# sql wpf sqlcommand


【解决方案1】:

看看这个: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();    
}

【讨论】:

  • @user1166905 SqlCommand 只要您的 sql 脚本中没有 GO 语句就可以工作。如果您严格要使用SqlCommand,则必须将文件拆分为单独的语句并使用循环使用它们。删除“GO”关键字并将脚本分成不同的批次。然后将每个批次作为自己的SqlCommand 执行。
  • 没有时间拆分它,必须尝试使用​​上面的Server,尽管添加了Microsoft.SqlServer,但似乎并不喜欢它
  • @user1166905 ADO.NET 类很遗憾不理解GO-Statements。因此,如果您的脚本包含GO,恐怕这是最有效的方法。
  • 你需要为上面的服务器添加什么引用,不管我做什么都不喜欢在代码中。
  • @user1166905 默认情况下,DLL 文件位于C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies。文件:Microsoft.SqlServer.Smo.dllMicrosoft.SqlServer.ConnectionInfo.dll
猜你喜欢
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多