Ankita
Ankita

Reputation: 1456

How to Create Tables in a SQL Server CE database file using C# code

I am creating a SQL Server Compact Edition database using C# code in a console application. Here is my code for creating database:

string con;

string fileName = "MiniProfilerData.sdf";
string password = "arcanecode";

if (File.Exists(fileName))
{
    File.Delete(fileName);
}

con = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine en = new SqlCeEngine(con);
en.CreateDatabase();

This code generates the MiniProfilerData.sdf file

Now I want to create tables in that .sdf file. I have a table creation script which will generates tables, here is the script Click Here

How can I generate tables using that TableCreationScript in my MiniProfilerData.sdf file?

Any idea?

Upvotes: 1

Views: 1478

Answers (1)

ErikEJ
ErikEJ

Reputation: 41759

You need to split the script into individual CREATE statements, the execute each (pseudo-code):

var scripts = TableCreationScript
    .Trim()
    .Replace("create", "#create")
    .Split(new []{'#'}, StringSplitOptions.RemoveEmptyEntries);

for each (var script in scripts)
{
    SqlCeCommand cmd = new SqlCeCommand(script);
    cmd.Connection = connection;
    cmd.ExecuteNonQuery();
}

Upvotes: 1

Related Questions