Potřebuji zkopírovat struktůru "tabulkaTest" a vytvořit prázdnou "tabulkaTest2" se stejnou struktůrou. Jde mi o to že když změním "tabulkaTest" tak ostatní tabulky se musejí vytvářet se stejnou struktůrou. Je to z důvodu pokud změním "tabulkaTest" abych nemusel stále na všech verzích programu měnit zdrojový kód. Víte někdo jak takový příkaz vypadá v SQLCE?
#1David Roško
Tak tady je mé řešení, :) pro ostatní kteří by řešili stejný problém
public void CloneTable(string originalTable, string newTable)
{
DataTable ss = GetDataTable(originalTable);
string tableString = GetCreateTableStatement(ss, newTable);
Query(tableString);
}
public DataTable GetDataTable(string table)
{
var cmd = new SqlCeCommand("SELECT * FROM "+table, con);
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
/// <summary>
/// Genenerates a SQL CE compatible CREATE TABLE statement based on a schema obtained from
/// a SqlDataReader or a SqlCeDataReader.
/// </summary>
/// <param name="tableName">The name of the table to be created.</param>
/// <param name="schema">The schema returned from reader.GetSchemaTable().</param>
/// <returns>The CREATE TABLE... Statement for the given schema.</returns>
public string GetCreateTableStatement(DataTable table, string tableName)
{
StringBuilder builder = new StringBuilder();
builder.Append(string.Format("CREATE TABLE [{0}] (", tableName));
foreach (DataColumn col in table.Columns)
{
SqlDbType dbType = GetSqlDBTypeFromType(col.DataType);
builder.Append("[");
builder.Append(col.ColumnName);
builder.Append("]");
builder.Append(" ");
builder.Append(GetSqlServerCETypeName(dbType, col.MaxLength));
builder.Append(", ");
}
if (table.Columns.Count > 0) builder.Length = builder.Length - 2;
builder.Append(")");
return builder.ToString();
}
/// <summary>
/// Gets the correct SqlDBType for a given .NET type. Useful for working with SQL CE.
/// </summary>
/// <param name="type">The .Net Type used to find the SqlDBType.</param>
/// <returns>The correct SqlDbType for the .Net type passed in.</returns>
public SqlDbType GetSqlDBTypeFromType(Type type)
{
TypeConverter tc = TypeDescriptor.GetConverter(typeof(DbType));
if (/*tc.CanConvertFrom(type)*/ true)
{
DbType dbType = (DbType)tc.ConvertFrom(type.Name);
// A cheat, but the parameter class knows how to map between DbType and SqlDBType.
SqlCeParameter param = new SqlCeParameter();
param.DbType = dbType;
return param.SqlDbType; // The parameter class did the conversion for us!!
}
else
{
throw new Exception("Cannot get SqlDbType from: " + type.Name);
}
}