SQL Mobile 2005 Script

  • Thread starter Thread starter Matheu
  • Start date Start date
M

Matheu

Hi, my question is if possible to create a script of a database, and run it
when i do the deploy of the application on the device ?....

Any link or sample to do it ?

Thanks a lot!
 
Usally the best place to put his code is in the BLL of the app. This allows a
nicer migration when your schema changes. Steve Lasker has some really cool
demos and ideas regarding this, check out his blog.

Also note, if you are using any version of Microsoft SQL Server Compact (not
sure about other products) you can't simply run a script which contains
multiple queries as the engine can only process one query at a time.

I've just copied this code from an app I'm working on a present. It simply
loads a script Tables_Create.sql stored in a resx file, if a database doesn't
not already exist it goes off any creates it from scratch:

//Now for the SQL.
StringBuilder sql = new StringBuilder();
List<string> commands = new List<string>();
System.IO.StringReader sr = new
System.IO.StringReader(Properties.StoredProcs.Tables_Create);
while (true)
{
string s = sr.ReadLine();
if (s == null)
break;

if (s.Length >= 2)
{
if (s.ToUpper().Substring(0, 2) != "GO")
sql.Append(s);
else
{
commands.Add(sql.ToString());
sql = new StringBuilder();
}
}
}

//Execute each statement in turn.
foreach (string s in commands)
{
cmd.CommandText = s;
connection.ExecuteNonQuery(cmd, null);
}

The query might look like:

CREATE TABLE Person (
PersonId int IDENTITY(1,1)
CONSTRAINT PersonId_PK PRIMARY KEY,
AddressId int NULL,
Name nvarchar(50),
ChangeStamp rowversion NOT NULL)
GO

CREATE INDEX Name_IX ON Person(Name)
GO

ALTER TABLE Person
ADD CONSTRAINT Name_FK
FOREIGN KEY(Name)
REFERENCES Address(AddressId)
ON DELETE CASCADE
GO

The code divides the query up, you get the idea. Of course the above is
wrapped in a transaction.
 
Sure, the cool thing about this is you can take that script and actually run
it through the management studio without change against a compact database or
mdf desktop database if you wanted. This also allows a nice abstraction of
SQL from your C# code. Although there is an exception to running the script
via management studio in that of course SQL compact 3.5 is not supported on
the management studio 2005, we will have to wait for server 2008 for that
which is currently in beta.
--
Simon Hart
Visual Developer - Device Application Development MVP
http://simonrhart.blogspot.com
 
Back
Top