I would like to store lengthy .sql scripts in my solution and execute them programmatically. I\'ve already figured out how to execute a string containing my sql script but I
Use QueryFirst. You put your sql in .sql template provided by the tool. Behind the scenes, QueryFirst compiles it as a resource and wires up the call to retrieve it at runtime. You only need to worry about calling Execute() on the generated wrapper class, and your results are accessible via generated POCOs. End to end type safety. Never have to remember a column name or datatype, plus the considerable advantages of having your sql where god intended... in a .sql file.
disclaimer: I wrote QueryFirst
Add the SQL files to your project then create a new resource file. Open up the SQL file and select 'Files' from the top-left drop down (default is Strings). Then hit add resource and navigate to/select the SQL file. This allows you to get SQL from the resource file without losing your type-safety like so:
The above is the process in Visual Studio 2010. I also wrote about this on my blog.
Add file to Resources, and set file to Resource, in code write:
String SQLCommand = NAMESPACE.Properties.Resources.ScriptDB.ToString()
First, edit the .sql file's properties so that it will be embedded as a resource.
Then use code similar to the following to retrieve the script:
string commandText;
Assembly thisAssembly = Assembly.GetExecutingAssembly();
using (Stream s = thisAssembly.GetManifestResourceStream(
"{project default namespace}.{path in project}.{filename}.sql"))
{
using (StreamReader sr = new StreamReader(s))
{
commandText = sr.ReadToEnd();
}
}