I want to have a function in C# with an argument which will be a table name in an SQL script it reads from. The code looks something like this in C#:
static void createTable(SqlConnection connection, String tableName, String fileName)
{
try
{
var fileContent = File.ReadAllText(fileName+".sql");
var sqlQueries = fileContent.Split(new[] { " GO " }, StringSplitOptions.RemoveEmptyEntries);
var cmd = new SqlCommand(fileName, connection);
SqlParameter param = cmd.Parameters.Add("@toBeReplaced", tableName);
connection.Open();
foreach (var query in sqlQueries)
{
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
connection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
When this function runs, I want it to execute the script in fileName.sql where it inserts into the table 'tableName'. The .sql script looks like this:
use myDatabase
GO
alter table TESTPersonsProject drop constraint FK_TESTPersonsProject_TESTproject
alter table TESTSideResearch drop constraint FK_TESTSideResearch_TESTproject
alter table TESTSamples drop constraint FK_TESTSamples_TESTproject
alter table @toBeReplaced drop constraint PK_TESTProject
alter table @toBeReplaced add tmp int;
GO
update @toBeReplaced set tmp=projectID where tmp is null
alter table @toBeReplaced drop column projectID
alter table @toBeReplaced add id_new int identity(1,1)
alter table @toBeReplaced add constraint PK_TESTProject primary key (id_new)
...
I know I could let the function look ugly and just have the query as a string. However, I do want to keep it clean and be able to use this function for more than just one query.
How do I declare and use this passed variable so that this query can affect more than just one specified table?
p.s. I'm using SQL SERVER 2008