我想运行从.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上运行脚本时,它可以工作。
答案 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)