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 haven't figured out how to read the string from a file that would be stored in the solution (under a /Scripts subfolder for example).
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With