针对SQL Server数据库执行脚本

3

我有一个.sql文件,其中包含与sql server 2008相关的数据库脚本,我想执行它来操作我的数据库。我希望将这个过程自动化,而不是手动操作。对我来说,有三种可用的选项:批处理文件、PowerShell或C#。我如何执行这个脚本,将会受到我的下一个问题的影响 - 如果脚本由于任何原因无法执行,我想在程序中得到通知。这将成为一组常规安装步骤的一部分,所以如果脚本不能正确地执行,我希望安装程序停止运行。


你为什么不使用 SQL Agent? - Wayne In Yak
你的安装流程的剩余部分是如何处理的? - NotMe
目前它是一个批处理文件,用于处理安装过程,但将作为回应此问题的一部分进行更改。 - amateur
7个回答

1

将其作为 SQL 代理作业运行,您可以设置 SQL 代理以在脚本失败时向您发送警报。


我希望它能够自动化,作为安装过程的一部分,就像问题中所说的那样。 - amateur
@业余爱好者,你可以自动化SQL Agent作业。它们可以使用一堆系统存储过程sp_add_job等来创建。 - Ben

0
以下是使用C#自动化脚本安装程序的过程:

C#代码

using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string")) {
    con.Open();
    SqlCommand cmd = new SqlCommand();
    string expression = "Parameter value";
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "Your Stored Procedure";
    cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
    cmd.Connection = con;
    using (IDataReader dr = cmd.ExecuteReader()) {
        if (dr.Read()) {
        }
    }
}

在你的项目中添加一个安装程序类引用 => 安装程序类
You can find below mentioned events for the installer process.
1. Install
2. Commit
3. Rollback
4. UNInstall

在上述事件中编写数据库连接和脚本执行代码。如果安装程序无法执行脚本,则会出现异常并自动转移到回滚事件。因此,最终的回滚事件将告诉用户由于执行脚本失败而无法完成安装...

0

0

我认为批处理更容易(但这是个人偏好)

runsqlscr.cmd

@echo off
REM :: building your script below, not needed if already created
REM echo Select * from PutTableHere where > %temp%\tmpsql.sql
REM echo "put rest of sql script here one line at a time" >> %temp%\tmpsql.sql
REM echo go >> %temp%\tmpsql.sql
REM echo.
REM echo script written
REM echo.
REM echo ready to execute script
REM :: delete pause if needed
REM pause
REM :: the actual command needed in script
REM sqlcmd -U thedbuser -P thepasswd -d thedbname -o resultsofscript.txt < %temp%\tmpsql.sql 
REM echo All done, displaying results
REM type resultofscript.txt
REM echo.

如果脚本已经构建完成,您可以跳过脚本的构建,只需将%temp%tmpsql.sql更改为您脚本的位置和名称即可。

在sqlcmd行中,您需要输入自己的“the*”值。

以上内容仅供测试使用,您的安装脚本所需的仅是sqlcmd行。

祝批处理愉快


0
你可以尝试使用SQL Server Management Objects (SMO - http://msdn.microsoft.com/en-us/library/ms162169.aspx),在安装过程中执行SQL脚本,这应该适用于你的情况。
在这段简短的代码中,你可以看到如何连接到SQL服务器实例,这里使用了Windows身份验证,但你也可以通过提供connection.Login和connection.Password来使用SQL身份验证。之后设置了事件处理程序,可以在脚本执行期间(ServerMessage, InfoMessage)和之后(StatementExecuted)触发。在这里同时使用ServerMessageInfoMessage有些多余,因为ServerMessage也会显示信息消息(SQL中错误严重性<10),但这是一个很好的演示方式。
在这个例子中,textBox1.Text包含一个T-SQL脚本,它将被执行: server.ConnectionContext.ExecuteNonQuery(textBox1.Text); 执行语句被try...catch包围以捕获执行期间的任何错误。
private void button1_Click(object sender, EventArgs e)
    {
        ServerConnection connection = new ServerConnection("stjepan-lap");
        connection.LoginSecure = true;
        Server server = new Server(connection);
        server.ConnectionContext.InfoMessage += new SqlInfoMessageEventHandler(ConnectionContext_InfoMessage);
        server.ConnectionContext.StatementExecuted += new StatementEventHandler(ConnectionContext_StatementExecuted);
        server.ConnectionContext.ServerMessage += new ServerMessageEventHandler(ConnectionContext_ServerMessage);

        //Executes T-Sql script
        try
        {
            server.ConnectionContext.ExecuteNonQuery(textBox1.Text);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
            if (ex.InnerException != null)
                Debug.WriteLine(ex.InnerException.Message);
        }

        server.ConnectionContext.Disconnect();
    }

    void ConnectionContext_ServerMessage(object sender, ServerMessageEventArgs e)
    {
        Debug.WriteLine(e.Error);
    }

    void ConnectionContext_StatementExecuted(object sender, StatementEventArgs e)
    {
        Debug.WriteLine(e.SqlStatement);
    }

    void ConnectionContext_InfoMessage(object sender, SqlInfoMessageEventArgs e)
    {
        Debug.WriteLine(e.Message);
    }

你应该引用SMO dll文件并在代码文件中放置适当的using语句

Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll 
....
using System;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

-1

你也可以将这个打包到存储过程中,并在那里使用一些错误处理。


这不能作为安装过程的一部分包含。 - amateur

-1
  • 通过 sqlcmd.exe 引导程序运行 - 更难处理错误
  • 通过您自己的自定义应用程序运行 - 最容易处理错误并提醒警报

这是安装过程的一部分,因此这些选项都不适用。 - amateur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接