views:

276

answers:

1

I would like to create my database tables in SMS then generate a script so C# can create the tables programmitically. I am currently hand coding each table at a time in visual studio. I think its far better to create the tables in SQL management studio then generate a script so c# can execute it latter on. Do you guys have any idea how to do this?

A: 

In SQL Management Studio (2008) you can right click on the database, select the Tasks option, then the Generate Scripts option. A wizard will walk you through generating a script or scripts for whatever you need in your database. You can then use this scripts in C# create tables/procedures/whatever.

Edit: The following chunk of code should execute sql scripts with GO statements in them (on SQL 2008 anyway)

string script = File.ReadAllText("script.sql");
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server();
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = "user";
server.ConnectionContext.Password = "pass";
server.ConnectionContext.ServerInstance = "instance";
server.Databases["master"].ExecuteNonQuery(script);
Tallek
I have done this and when I try to execute it with c#, it complains about the "GO" commands
Luke101
The `GO` command is not valid T-SQL; it is a construct of SSMS used to separate batches. You'll need to split the script into executable sections (which it already is; they're just pasted together with `GO`).
Jay
Thanks..Jay. I didn't know that
Luke101