Exemplo n.º 1
0
        public static string FromDataTable(string tableName, DataTable schema, int[] primaryKeys = null)
        {
            var sqlTable = new SqlTableDefinition
            {
                TableName = tableName
            };

            // columns
            foreach (DataRow column in schema.Rows)
            {
                var sqlCol = new SqlColumnDefinition();

                if (!(schema.Columns.Contains("IsHidden") && (bool)column["IsHidden"]))
                {
                    sqlCol.ColumnName = column["ColumnName"].ToString();
                    sqlCol.DataType   = CreateTableSqlInternal.SqlGetType(column);

                    if (schema.Columns.Contains("AllowDBNull") && ((bool)column["AllowDBNull"] == false))
                    {
                        sqlCol.IsNullable = false;
                    }
                }

                sqlTable.ColumnDefinitions.Add(sqlCol);
            }

            // primary keys
            var hasKeys = (primaryKeys != null) && (primaryKeys.Length > 0);

            if (hasKeys)
            {
                // user defined keys
                foreach (var key in primaryKeys)
                {
                    sqlTable.PrimaryKeyColumnNames.Add(schema.Rows[key]["ColumnName"].ToString());
                }
            }
            else
            {
                // check schema for keys
                sqlTable.PrimaryKeyColumnNames.AddRange(schema.GetPrimaryKeys());
                hasKeys = sqlTable.PrimaryKeyColumnNames.Count > 0;
            }

            return(CreateTableSqlInternal.FromSqlTableDefinition(sqlTable));
        }
Exemplo n.º 2
0
        public static string FromDataTable2(string tableName, DataTable table)
        {
            var sql = "CREATE TABLE [" + tableName + "] (\n";

            // columns
            foreach (DataColumn column in table.Columns)
            {
                sql += "[" + column.ColumnName + "] " + CreateTableSqlInternal.SqlGetType(column) + ",\n";
            }
            sql = sql.TrimEnd(',', '\n') + "\n";
            // primary keys
            if (table.PrimaryKey.Length > 0)
            {
                sql += "CONSTRAINT [PK_" + tableName + "] PRIMARY KEY CLUSTERED (";
                foreach (var column in table.PrimaryKey)
                {
                    sql += "[" + column.ColumnName + "],";
                }
                sql = sql.TrimEnd(',') + "))\n";
            }

            return(sql);
        }