I have a table in multiple databases that I need to update and add default values for multiple columns within that table.
I've got the following constraints to add into the table:
ALTER TABLE ProcessQUeue
ADD CONSTRAINT C_bSaveAfter DEFAULT 0 FOR bSaveAfter;
GO
ALTER TABLE ProcessQueue
ADD CONSTRAINT C_bForcePassword DEFAULT 0 FOR bForcePassword;
GO
ALTER TABLE ProcessQueue
ADD CONSTRAINT C_bIsComplete DEFAULT 0 FOR bIsComplete;
GO
If I run the above in SQL Server Management Studio; it works great.
I then removed the constraints and tried running it through my code:
private static string AlterTable(string szQuery, string szReferencedFileName)
{
try
{
using (SqlConnection aConnection = new SqlConnection(szConnectionString))
{
aConnection.Open();
using (SqlCommand dbCommand = new SqlCommand(szQuery, aConnection))
{
dbCommand.ExecuteNonQuery();
}
}
}
//Some usual exception handling
catch (SqlException e)
{
string szMsg = e.Message.ToString() + " " + e.ErrorCode.ToString();
if (Environment.UserInteractive)
Console.WriteLine("\r\n" + szMsg + "\r\n - Query: " + szQuery + "\r\n - " + szConnectionString + "\r\n");
return "ERR:SQLDB/AddTable: " + szMsg;
}
catch (Exception e)
{
string szMsg = e.Message.ToString();
if (Environment.UserInteractive)
Console.WriteLine("\r\n" + szMsg + "\r\n - Query: " + szQuery + "\r\n - " + szConnectionString + "\r\n");
return "ERRex:CheckSQLDB/AddTable: " + szMsg;
}
return string.Empty;
}
I get an error:
Incorrect syntax near 'go'.
Incorrect syntax near 'go'.
Incorrect syntax near 'for'.
In some cases, I've had to remove the GO from the query so I tried that as well and the syntax error is change from 'go' to 'for'.
Why would this work in SQL Server Management Studio and not in the C# application?
GOis a separator for SQL batches used by SQL Server Management Studio - but it's NOT a proper SQL statement - you cannot use this in code you execute from your C# app