解析查询时出错。如何解决?

There was an error parsing the query. How to resolve it?

我想要 运行 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();
    }
}

不知道怎么解决。当我 运行 直接在数据库上编写脚本时它有效。

  • 请在 Alter the table
  • 之前使用 Go 关键字

已解决:

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'

你必须运行每个语句作为一个单独的命令,如果你用 GO 分隔每个命令,你可以使用像辅助函数这样的代码来分隔成命令:

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

如您所见,我正在使用 DbUp 包中的 SqlCommandReaderStreamed 来执行此操作