我在VS 2017(SSDT 2017)的DB项目中使用.tt脚本。我们手动创建暂存表结构,然后t4脚本根据暂存表结构生成最终目标表。
我有这个代码来获取列和它们的数据类型来创建我的最终目标表,但它看起来如果其中一个字段被定义为varchar(max),那么生成的字段就会得到varchar数据类型,就是这样.下面是脚本的示例。
foreach (var col in table.GetReferenced(Table.Columns))
{
string columnText;
string columnName = col.Name.Parts[2];
// this attempts to limit to only columns from the source. there's gotta be a cleaner way.
if (!skipColumns.Contains(columnName))
{
int length = col.GetProperty<int>(Column.Length);
int precision = col.GetProperty<int>(Column.Precision);
int scale = col.GetProperty<int>(Column.Scale);
string suffix;
if (length != 0)
{
suffix = String.Format("({0})", length);
}
else if (precision != 0)
{
suffix = String.Format("({0},{1})", precision, scale);
}
else if (precision == 0 && scale != 0)
{
suffix = String.Format("({0})", scale);
}
else
{
suffix = "";
}
bool nullable = col.GetProperty<bool>(Column.Nullable);
string nullText = nullable ? "NULL" : "NOT NULL";
string dataType = col.GetReferenced(Column.DataType).FirstOrDefault().Name.ToString();
columnText = String.Format("[{0}] {1}{2} {3}", columnName, dataType, suffix, nullText);
WriteLine(" " + columnText + ",");
}
}
如何在t4脚本中处理varchar(max)?
这里的答案。你要用下面的方法,然后比较一下。
bool isMax = col.GetProperty<bool>(Column.IsMax);
...
if (isMax)
{
suffix = String.Format("({0})", "max");
}