解析查询时出错。怎么解决呢?

时间:2019-03-27 11:43:44

标签: c# parsing sql-server-ce executenonquery

我想运行从.sql文件中首先读取的sql语句。

我收到此错误: {"There was an error parsing the query. [ Token line number = 13,Token line offset = 1,Token in error = ALTER ]"}

.sql文件中有我的sql语句:

CREATE TABLE [Test]
(
   [Id] INT NOT NULL IDENTITY (1,1),
   [DatabaseVersion] NVARCHAR(20) NOT NULL,
   [Autorun] BIT,
   [CurrentCulture] NVARCHAR(10),
   [MailNotificationEnabled] BIT,
   [RefreshInterval] INT,
   [ModifiedDate] DATETIME NOT NULL,
   [schemat] NVARCHAR(255)
)

ALTER TABLE [Test] ADD CONSTRAINT [PK_Test] PRIMARY KEY ([Id])

UPDATE [AppConfig]
SET [DatabaseVersion] = '0.12'

正在读取文件:

string oldVersion = GetOldDatabaseVersion();
string sqlScript = "";
sqlScript = GetScriptFromAssembly(oldVersion, 
ConfigurationSettings.ValidDatabaseVersion);

ExecuteNonQuery(CommandType.Text, sqlScript);

ExecuteNonQuery方法:

public int ExecuteNonQuery(CommandType type, string sql)
{
    using (SqlCeConnection connection = CreateConnection())
    {
        return ExecuteNonQuery(connection, type, sql);
    }
}

private int ExecuteNonQuery(SqlCeConnection connection, CommandType type, string sql)
{
    using (SqlCeCommand command = new SqlCeCommand())
    {
        command.Connection = connection;
        command.CommandType = type;
        command.CommandText = sql;

        return command.ExecuteNonQuery();
    }
}

我不知道该如何解决。当我直接在db上运行脚本时,它可以工作。

3 个答案:

答案 0 :(得分:2)

已解决:

string sqlScript = GetScriptFromAssembly(GetOldDatabaseVersion(), ConfigurationSettings.ValidDatabaseVersion);

string[] scripts = sqlScript.Split(new string[] { @"/*$$*/" }, StringSplitOptions.None);

foreach(var script in scripts)
    ExecuteNonQuery(CommandType.Text, script);

在sql中添加了定界符:

CREATE TABLE [Test]
(
   [Id] INT NOT NULL IDENTITY (1,1),
   [DatabaseVersion] NVARCHAR(20) NOT NULL,
   [Autorun] BIT,
   [CurrentCulture] NVARCHAR(10),
   [MailNotificationEnabled] BIT,
   [RefreshInterval] INT,
   [ModifiedDate] DATETIME NOT NULL,
   [schemat] NVARCHAR(255)
)

/*$$*/
ALTER TABLE [Test] ADD CONSTRAINT [PK_Test] PRIMARY KEY ([Id])

/*$$*/
UPDATE [AppConfig]
SET [DatabaseVersion] = '0.12'

答案 1 :(得分:1)

您必须将每个语句作为单独的命令运行,如果使用GO分隔每个命令,则可以使用诸如helper函数之类的代码来分隔为命令:

https://github.com/ErikEJ/SqlCeToolbox/blob/master/src/API/Repositories/ServerDBRepository.cs#L639

如您所见,我正在使用DbUp软件包中的SqlCommandReaderStreamed

答案 2 :(得分:-1)

  • 请在更改表格之前使用转到关键字