Answer the question
In order to leave comments, you need to log in
How to use variables (SqlParameter) in query with ALTER TABLE from .NET application?
I am writing a utility in C#, the utility should be able to automatically create new fields in SQL Server tables.
In this case, the NOT NULL fields must be filled with default values (or given values).
Those. I do something like this:
// формирую команду
//..........................
StringBuilder alter = new StringBuilder("ALTER TABLE [" + _tableName + "] ADD ");
foreach (var c in _createColumns)
{
alter.Append("[" + c.Name + "] " + c.DbType);
//.........................
// если встречаю not null поле
if (c.AllowNull==false)
alter.Append(" NOT NULL DEFAULT(@" + c.Name + ")");
//.........................
// И при выполнении запроса формирую параметры по умолчанию
public SqlParameter[] GetDefaultAlterParameters()
{
return _createColumns.Select(c => new SqlParameter(c.Name, GetDefaultValue(c.DotNetType))).ToArray();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question