且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ASP.NET C#一次执行多个SQL命令

更新时间:2023-12-05 23:02:40

GO是一个SQL-Server-Management-Studio特定命令,而不是T-SQL的一部分。



如果你想使用带有GO命令的SQL脚本,请参考:

c# - 执行一个大型SQL脚本(使用GO命令) - Stack Overflow [ ^ ]



否则你必须单独执行这些语句(我建议使用使用 -statements for Sql *** * -objects):



"GO" is a SQL-Server-Management-Studio specific command and not part of T-SQL.

If you would want to use SQL-scripts with "GO"-commands please refer to this:
c# - Execute a large SQL script (with GO commands) - Stack Overflow[^]

Otherwise you would have to execute these statements separately (and I suggest using using-statements for Sql****-objects):

using (var connection = new SqlConnection("your connection string here"))
{
    connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandText = "CREATE DATABASE dbTest;";
        command.ExecuteNonQuery();

        command.CommandText = "USE dbTest;";
        command.ExecuteNonQuery();
    }
}



连接字符串***不要在指定位置硬编码,而应从配置文件中读取。



请注意,USE命令只会影响同一连接上的以下命令,所以在这个例子中它很没用。


The connection string should best not be hardcoded at the indicated position but be read from a configuration file.

Note that the "USE"-command will affect only the following commands on the same connection, so in this example it's pretty useless.