我正在维护一个简单的数据库工具,它在我们的 EF 上执行 CreateDatabase
型号,并使用 SMO运行一些 .sql 脚本。
目前使用:
var svrConnection = new ServerConnection(sqlConnection);
var server = new Server(svrConnection);
server.ConnectionContext.ExecuteNonQuery(fullSqlScript);
有没有办法在不使用 SMO 的情况下在 .Net 中执行 TSQL 脚本?
或者,有没有一种方法可以在应用程序中成功使用 SMO,而无需在我运行它的服务器上安装它?
除了我的工具的程序集 xcopy 之外,任何对我有用的替代方案都不需要安装在盒子上。它还必须保证脚本将以完全相同的方式运行,而无需额外的测试/验证。
脚本使用 GO
等,不能/不应该分解 - 它们由第三方工具 (aspnet_regsql.exe
) 生成,并由手(但此时已经陈旧),所以如果可以避免,我不想碰它们。
我很确定这些建议 in the comments on this answer是错误的,因为我很确定 GO
不能直接用 ;
替换。如果我错了,请告诉我:)
我正在尝试解决这个问题:
Could not load file or assembly 'Microsoft.SqlServer.SqlClrProvider, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
The fix mentioned here是安装 SMO,这需要其他软件包,这对我来说并不理想。
最终解决方案,基于 Russell McClure's answer :
最后我将以 sqlcmd.exe 结束,因为为它编写的脚本(其中包含 GO
的任何内容)可能会做太多事情而无法通过 SqlCommand.ExecuteNonQuery 进行复制
在我自己的代码中。由于它具有与 SMO 相同级别的依赖性,并且需要一些工作才能以编程方式干净的方式进行包装,所以我将坚持使用 SMO。
我提到的所有库和工具都是 :
最佳答案
通过 sqlcmd.exe 运行您的 T-SQL .
或者,我通常做的是实际读取文件内容(我的 sql 文件通常是嵌入式资源),然后将其传递给此函数以将其拆分为 ADO.NET 可接受的批处理:
public static string[] ParseSqlStatementBatch(string sqlStatementBatch)
{
// split the sql into seperate batches by dividing on the GO statement
Regex sqlStatementBatchSplitter = new Regex(@"^\s*GO\s*\r?$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
return sqlStatementBatchSplitter.Split(sqlStatementBatch);
}
这是一个用法示例:
string[] sqlStatements = DataAccess.DatabaseWrapper.ParseSqlStatementBatch(FileContents);
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandTimeout = Registry.RegistryWrapper.GetSqlCommandTimeout();
foreach (string sqlStatement in sqlStatements)
{
if (sqlStatement.Length > 0)
{
command.CommandText = sqlStatement;
command.ExecuteNonQuery();
关于.net - 不使用 SMO 执行 TSQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073170/