2012-01-08 70 views
0

我刚刚发现SQL Server CE不允许您批量查询。所以给定一大串SQL语句,我试图将它们分开,然后单独执行它们。的问题是,某些查询由单个线和其他2分隔对于实施例说,我有以下查询:按命令分割SQL字符串

CREATE TABLE [Settings] (
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Name] [nvarchar](100) NOT NULL, 
    [Value] [nvarchar](100) NULL 
) 

ALTER TABLE [Settings] ADD 
    CONSTRAINT [PK_Settings] PRIMARY KEY ([Id]) 

INSERT INTO [Settings] ([Name, [Value]) VALUES ('SiteUrl', 'http://localhost') 
INSERT INTO [Settings] ([Name], [Value]) VALUES ('AssetsUrl', '/Assets') 

我想每个SQL命令拆分成一个字符串数组。感谢帮助。由于

+0

在哪里这些查询定义? – Oded 2012-01-08 12:22:09

+0

为什么查询被2行分隔的问题? – atoMerz 2012-01-08 12:24:22

回答

2

此代码分割你大肉SQL字符串separete SQL命令

string str = @"CREATE TABLE [Settings] (
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [Name] [nvarchar](100) NOT NULL, 
    [Value] [nvarchar](100) NULL 
) 

ALTER TABLE [Settings] ADD 
    CONSTRAINT [PK_Settings] PRIMARY KEY ([Id]) 

INSERT INTO [Settings] ([Name, [Value]) VALUES ('SiteUrl', 'http://localhost') 
INSERT INTO [Settings] ([Name], [Value]) VALUES ('AssetsUrl', '/Assets')"; 

// Replace all [new line] to [space] 
while (str.Contains(Environment.NewLine)) 
{ 
    str = str.Replace(Environment.NewLine, " ");   
} 

// Array of all sql commands using in query 
string[] sqlCommands = { "CREATE TABLE", "ALTER TABLE", "INSERT INTO" }; 

// Insert before each sql expression new line 
foreach (string sqlCommand in sqlCommands) 
{ 
    str = str.Replace(sqlCommand, Environment.NewLine + sqlCommand); 
} 

// Split big sql string to separate commands, and remove empty strings 
string[] arr = str.Split(new string[] { Environment.NewLine }, 
      StringSplitOptions.None); 
arr = arr.Where(cmd => !String.IsNullOrEmpty(cmd)).ToArray(); 

// Execute sql commands 
foreach (string command in arr) 
{ 
    Console.WriteLine(">> {0}{1}", command, Environment.NewLine); 
} 
+0

伟大的工作,感谢。 – nfplee 2012-01-09 11:00:10