コード例 #1
0
        protected override string GetCreateTableSql()
        {
            var           identity    = "IDENTITY(1,1)";
            StringBuilder builder     = new StringBuilder($"USE {Schema.Database}; IF OBJECT_ID('{Schema.TableName}', 'U') IS NULL CREATE table {Schema.TableName} (");
            StringBuilder columnNames = new StringBuilder();

            if (Primary.Count == 0)
            {
                foreach (var p in Columns)
                {
                    columnNames.Append($",[{p.Name}] {ConvertToDbType(p.DataType)} NULL");
                }
            }
            else
            {
                foreach (var p in Columns)
                {
                    var identityPart = AutoIncrement.Contains(p.Name) ? identity : "";
                    var nullPart     = Primary.Any(k => k.Name == p.Name) ? "NOT NULL" : "NULL";

                    columnNames.Append($",[{p.Name}] {ConvertToDbType(p.DataType)} {identityPart} {nullPart}");
                }
            }

            builder.Append(columnNames.ToString().Substring(1, columnNames.Length - 1));
            builder.Append(Primary == null || Primary.Count == 0 ? (columnNames.Length == 0 ? "" : ",") + "[__id] [int] IDENTITY(1,1) NOT NULL," : ",");
            string primaryKey = Primary == null || Primary.Count == 0 ? "[__id] ASC" : string.Join(", ", Primary.Select(p => $"[{p.Name}] ASC"));

            builder.Append(
                $" CONSTRAINT [PK_{Schema.TableName}] PRIMARY KEY CLUSTERED ({primaryKey.Substring(0, primaryKey.Length)})WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]) ON[PRIMARY];");

            foreach (var index in Indexs)
            {
                string name            = string.Join("_", index.Select(c => c));
                string indexColumNames = string.Join(", ", index.Select(c => $"[{c}]"));
                builder.Append($"CREATE NONCLUSTERED INDEX [index_{name}] ON {Schema.TableName} ({indexColumNames.Substring(0, indexColumNames.Length)});");
            }

            foreach (var unique in Uniques)
            {
                string name             = string.Join("_", unique.Select(c => c));
                string uniqueColumNames = string.Join(", ", unique.Select(c => $"[{c}]"));
                builder.Append($"CREATE UNIQUE NONCLUSTERED INDEX [unique_{name}] ON {Schema.TableName} ({uniqueColumNames.Substring(0, uniqueColumNames.Length)});");
            }
            return(builder.ToString());
        }