我正在開發多租戶應用程序,所以我需要從每個新客戶端的代碼創建數據庫。我已經產生,從SSMS「生成腳本」工具我的架構的劇本,然後我試過如下:從腳本創建數據庫時,關鍵字'USE'錯誤附近的語法不正確
public static void CreateIfNotExist(string path) // the path where the script for creating database is located
{
var db = System.Web.HttpContext.Current.Session["dbName"].ToString();
using (var con = new SqlConnection("Data Source=.; uid=sa; pwd=password;"))
{
con.Open();
var xmlStr = File.ReadAllText(path);
var str = XElement.Parse(xmlStr);
foreach (var item in str.Elements())
{
var query = "CREATE DATABASE " + db + Environment.NewLine + "GO" + Environment.NewLine + "USE " + db + Environment.NewLine + "GO" + Environment.NewLine;
var scriptToRun = File.ReadAllText(item.Value);
query += scriptToRun;
SqlCommand cmd = new SqlCommand(query, con);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
}
}
然後我的腳本:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[ACOD](
[id] [numeric](10, 0) NOT NULL,
[serial] [numeric](10, 0) NULL,
[name] [varchar](250) NULL,
CONSTRAINT [PK_ACOD] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING OFF
GO
CREATE TABLE [dbo].[AGZH](
[id] [numeric](10, 0) NOT NULL,
[number] [numeric](10, 0) NULL,
[date] [smalldatetime] NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_AGZH] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
這是腳本的只是一部分。實際上,我有100多個表,每個表有50多列。
現在,當我使用上面寫它給了我下面的異常C#代碼:關鍵字「使用」附近
不正確的語法。數據庫'databaseName'不存在 。確保名稱輸入正確。
但是,當我從Visual Studio中的文本可視化工具獲取腳本並在SSMS中執行它時,它會成功運行並創建新的數據庫名稱。
我在做什麼錯?請幫忙。
謝謝。有效。我隔離了命令。首先,我只執行CREATE DATABASE命令,然後將其餘命令作爲另一個命令。此外,我從腳本中刪除所有'GO'命令。 非常感謝。我真的把我的頭髮拉過來。 –