How can I execute a .sql from C#?

前端 未结 6 602
旧时难觅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 20:48

    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;
    

    You shouldn't need SMO to execute queries. Try using the SqlCommand object instead. Remove these using statements. Use this code to execute the query:

     SqlConnection conn = new SqlConnection(sqlConnectionString);
     SqlCommand cmd = new SqlCommand(script, conn);
     cmd.ExecuteNonQuery();
    

    Also, remove the project reference to SMO. Note: you will want to clean up resources properly.

    Update:

    The ADO.NET libraries do not support the 'GO' keyword. It looks like your options are:

    1. Parse the script. Remove the 'GO' keywords and split the script into separate batches. Execute each batch as its own SqlCommand.
    2. Send the script to SQLCMD in the shell (David Andres's answer).
    3. Use SMO like the code from the blog post.

    Actually, in this case, I think that SMO may be the best option, but you will need to track down why the dll wasn't found.

提交回复
热议问题