在C#

时间:2018-10-19 08:00:41

标签: c# smo

我在程序中运行SQL脚本时遇到问题。这是程序的代码

        string databaseName = "TestDB";
        Server srv1 = new Server(@"TestServer/ABCUser");   // connects to default instance  
        srv1.ConnectionContext.LoginSecure = false;   // set to true for Windows Authentication  
        srv1.ConnectionContext.Login = "sa";
        srv1.ConnectionContext.Password = "abcde123*";
try
        {
            Console.WriteLine(srv1.Information.Version);   // connection is established  
            if(srv1.Databases[databaseName] == null)
            {
                Microsoft.SqlServer.Management.Smo.Database db;
                db = new Microsoft.SqlServer.Management.Smo.Database(srv1, databaseName);
                db.Create();
                db = srv1.Databases[databaseName];
                Console.WriteLine(db.CreateDate);
            }

            else
            {
                Console.WriteLine("DB Already Exists!");
            }
            string sqlScript = File.ReadAllText(@"D:\Projects\TrainingProject\src\TrainingDatabase\Scripts\Tables\Script01-table.sql");
            Console.WriteLine(sqlScript);
            srv1.ConnectionContext.ExecuteNonQuery(sqlScript);

        }
        catch (ConnectionFailureException e)
        {
            Console.WriteLine("Error in connecting to the sql server " + e.Message);
        }

这是SQL脚本

IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'FileTypes') BEGIN
CREATE TABLE FileTypes (
    FileTypeID tinyint IDENTITY(1,1) NOT NULL,
    TypeName varchar(500) NOT NULL

    CONSTRAINT PK_FileTypes PRIMARY KEY(FileTypeID)
)

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'FileTypes')
    PRINT 'Created table FileTypes'
ELSE
    PRINT 'Failed to create table FileTypes'

END

到目前为止,我已经测试过:

  1. 我设法获取服务器信息版本(成功连接到服务器)

  2. 我可以从程序中创建数据库

  3. 当我将脚本用作Microsoft SQL Server Management Studio上的查询时,脚本正在运行

  4. Console.WriteLine(sqlScript);命令确实显示了正确的SQL脚本

问题是srv1.ConnectionContext.ExecuteNonQuery(sqlScript);无法正常工作。

有人知道答案吗?

这些是我用于参考的stackoverflow问题:Execute a large SQL script (with GO commands)

1 个答案:

答案 0 :(得分:1)

事实证明我在这一行中犯了一个错误:srv1.ConnectionContext.ExecuteNonQuery(sqlScript);

它应该在主数据库中创建表:

srv1.Databases[databaseName].ExecuteNonQuery(sqlScript);