Beispiel #1
0
 /// <summary>
 /// Creates a command string creating a table with the given schema.
 /// </summary>
 /// <param name="tablename">The name of the new table to create.</param>
 /// <returns>A command string for creating a table with the given schema.</returns>
 public string CreateTableScript(string tablename)
 {
     if (createTable == null)
     {
         // lazy evaluation
         StringBuilder sql = new StringBuilder(" (");
         for (int i = 0; i < Columns.Count; i++)
         {
             SchemaTableColumn col = Columns[i];
             sql.AppendFormat(
                 "\n\t[{0}] {1}{2}{3}{4},",
                 col.Name,
                 col.DbTypeFullName,
                 col.IsIdentity ? " IDENTITY" : "",
                 col.IsAutoIncrement ? "(1,1)" : "",
                 !col.AllowDBNull ? " NOT NULL" : "");
         }
         if (UniqueColumns.Count > 0)
         {
             sql.AppendFormat("\r\n CONSTRAINT AK_{0} UNIQUE ({0})," + UniqueColumns[0], string.Join(",", UniqueColumns));
         }
         string pkeyConstraint = "";
         if (PrimaryKey.Count > 0)
         {
             sql.Append("\r\n CONSTRAINT PK_");
             pkeyConstraint = tablename + string.Format(" PRIMARY KEY ({0})\n);", string.Join(",", PrimaryKey.Select(col => col.Name)));
         }
         else
         {
             sql.Remove(sql.Length - 1, 1).Append("\n);");                     // remove last comma
         }
         createTable = "CREATE TABLE " + tablename + sql.ToString() + pkeyConstraint;
     }
     return(createTable);
 }
Beispiel #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaTable"/> class.
        /// </summary>
        /// <param name="schema">The results from <see cref="SqlDataReader.GetSchemaTable"/>.</param>
        public SchemaTable(DataTable schema)
        {
            SchemaTableColumn[]      columns    = new SchemaTableColumn[schema.Rows.Count];
            List <SchemaTableColumn> uniqueCols = new List <SchemaTableColumn>();
            List <SchemaTableColumn> pkey       = new List <SchemaTableColumn>();

            for (int i = 0; i < schema.Rows.Count; i++)
            {
                columns[i] = new SchemaTableColumn(schema, i);
                if (columns[i].IsKey)
                {
                    pkey.Add(columns[i]);
                }
                if (columns[i].IsUnique)
                {
                    uniqueCols.Add(columns[i]);
                }
            }
            Columns       = columns;
            UniqueColumns = uniqueCols;
            PrimaryKey    = pkey;
        }