如何在 t4 脚本中处理 varchar(max)?

How to handle varchar(max) in t4 script?

我在数据库项目中使用 VS 2017(SSDT 2017) 中的 .tt 脚本。我们手动创建暂存 tables 结构,然后 T4 脚本根据暂存 table 结构生成最终目标 tables。

我有此代码来获取列及其数据类型以创建我的最终目标 tables 但它会查看其中一个字段是否定义为 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");
                    }