How can I execute a .sql from C#?

前端 未结 6 616
旧时难觅i
旧时难觅i 2020-12-04 20:05

For some integration tests I want to connect to the database and run a .sql file that has the schema needed for the tests to actually run, including GO statements. How can I

6条回答
  •  时光说笑
    2020-12-04 21:07

    MSVCR80 is the Visual C++ 2005 runtime. You may need to install the runtime package. See http://www.microsoft.com/downloads/details.aspx?FamilyID=200b2fd9-ae1a-4a14-984d-389c36f85647&displaylang=en for more details.

    In addition to resolving the DLL issue and Matt Brunell's answer (which I feel is more appropriate for what you're trying to do), you can use the SQLCMD command line tool (from the SQL Client tools installation) to execute these SQL scripts. Just be sure it's on your path so you don't struggle with path locations.

    This would play out like so:

    Actual command:

    SQLCMD -S myServer -D myDatabase -U myUser -P myPassword -i myfile.sql
    

    Parameters (case matters):

    S: server
    d: database
    U: User name, only necessary if you don't want to use Windows authentication
    P: Password, only necessary if you don't want to use Windows authentication
    i: File to run
    

    Code to execute SQL files:

    var startInfo = new ProcessStartInfo();
    startInfo.FileName = "SQLCMD.EXE";
    startInfo.Arguments = String.Format("-S {0} -d {1}, -U {2} -P {3} -i {4}",
                                        server,
                                        database,
                                        user,
                                        password,
                                        file);
    Process.Start(startInfo);
    

    See http://msdn.microsoft.com/en-us/library/ms162773.aspx for more information on the SQLCMD tool.

提交回复
热议问题