I am developing a multi tenant application so I need to create database from code for every new client. I have generated script of my schema from SSMS "Generate Script" utility, then I tried the following:
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)
{
}
}
}
}
And my script is:
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
This is just a portion of script. In actual, I have 100+ tables with every table have more than 50 columns.
Now when I use the C# code written above it gave me the following exception:
Incorrect syntax near the keyword 'USE'. Database 'databaseName' does not exist. Make sure that the name is entered correctly.
But when I get the script from text visualizer in Visual Studio and execute it in SSMS, it runs successfully and created the new database name.
What am I doing wrong? Please help.