Skip to content

Instantly share code, notes, and snippets.

@sphingu
Last active December 18, 2015 12:59
Show Gist options
  • Save sphingu/5787182 to your computer and use it in GitHub Desktop.
Save sphingu/5787182 to your computer and use it in GitHub Desktop.
Generate Table Create Script Code Behind in C#
private void btnBackupWin_Click(object sender, RoutedEventArgs e)
{
try
{
if (_conSource != null && dgSource.Visibility==Visibility.Visible)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog
{
Description = @"Select Folder to store backup file : "
};
var result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
if (_conSource.DataSource != null && (!_conSource.DataSource.Contains('.') && !_conSource.DataSource.Contains(Environment.MachineName)))
{
string temp = "\\\\" + _conSource.DataSource + "\\" + dialog.SelectedPath.Replace(':', '$');
if (!Directory.Exists(temp))
Directory.CreateDirectory(temp);
}
_conSource.Open();
SqlCommand command = new SqlCommand("backup database " + _conSource.Database + " to disk='" + dialog.SelectedPath + "\\" + _conSource.Database + "_FullBackup.bak' with init,stats=10", _conSource);
command.ExecuteNonQuery();
if (_conSource.DataSource != null && (_conSource.DataSource.Contains('.') || _conSource.DataSource.Contains(Environment.MachineName)))
OpenFolder(dialog.SelectedPath + "\\" + _conSource.Database + "_FullBackup.bak");
else
OpenFolder("\\\\" + _conSource.DataSource + "\\" + dialog.SelectedPath.Replace(':', '$').TrimEnd(new[] { '\\'}) + "\\" + _conSource.Database + "_FullBackup.bak");
}
}
else
{
MessageBox.Show("Please Enter Source Database Details");
}
}
catch (Exception ex)
{
MessageBox.Show("Error in Backup Click : " + ex.Message);
}
finally
{
if (_conSource != null)
if (_conSource.State == ConnectionState.Open)
_conSource.Close();
}
}
private void btnRestoreWin_Click(object sender, RoutedEventArgs e)
{
try
{
if (_conDest != null && dgDestination.Visibility == Visibility.Visible)
{
// Create OpenFileDialog
var dlg = new Microsoft.Win32.OpenFileDialog
{
DefaultExt = ".bak",
Filter = "Backup Files (.bak)|*.bak"
};
// Set filter for file extension and default file extension
// Display OpenFileDialog by calling ShowDialog method
var result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
if (MessageBox.Show("Are you sure you restore?", "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
string filename = dlg.FileName;
string db = _conDest.Database;
//-------------------Retrive the Logical file name of the database from backup.
_query = "RESTORE FILELISTONLY FROM DISK = '" + filename + "'";
_dt = GetData(_query, _conDest);
SqlCommand command;
//-----------------Make Database to single user Mode
//command = new SqlCommand("ALTER DATABASE "+db+" SET SINGLE_USER WITH ROLLBACK IMMEDIATE", conDest);
_conDest.Open();
//command.ExecuteNonQuery();
command = new SqlCommand("use master", _conDest);
command.ExecuteNonQuery();
//command = new SqlCommand(@"restore database " + db + " from disk = '" + filename + "' WITH REPLACE", conDest);
_query = "RESTORE DATABASE " + db + " FROM DISK = '" + filename + "' WITH MOVE '" + _dt.Rows[0][0] + "' TO '" + _dt.Rows[0][1] + "'," +
" MOVE '" + _dt.Rows[1][0] + "' TO '" + _dt.Rows[1][1] + "' ,REPLACE";
command = new SqlCommand(_query, _conDest);
command.ExecuteNonQuery();
//command = new SqlCommand("ALTER DATABASE " + db + " SET MULTI_USER",conDest);
//command.ExecuteNonQuery();
btnDestination.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
MessageBox.Show("Database Has been restored database", "Restoration", MessageBoxButton.OK);
_conDest.Close();
}
}
}
else
{
MessageBox.Show("Please Enter Destination Database Details");
}
}
catch (Exception ex)
{
MessageBox.Show("Error in Restore Click : " + ex.Message);
}
finally
{
if (_conDest != null)
if (_conDest.State == ConnectionState.Open)
_conDest.Close();
}
}
private void TableDropIfExist(string tableName)
{
string sql = "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'" + tableName + "') AND type=N'U') DROP Table " + tableName + " ";
ExeNonQuery(sql, _conDest);
}
public string GetCreateFromDataTableSql(string tableName, DataTable table)
{
string query = "SELECT * FROM information_schema.columns WHERE table_name = '" + tableName + "' ";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
da.Fill(dt);
string sql = "CREATE TABLE [" + tableName + "] (\n";
// columns
foreach (DataRow dr in dt.Rows)
{
sql += "[" + dr["COLUMN_NAME"] + "] ";
string type = dr["DATA_TYPE"].ToString();
sql += type;
if (dr["CHARACTER_MAXIMUM_LENGTH"] != null && type != "image" && type != "ntext")
{
if (dr["CHARACTER_MAXIMUM_LENGTH"].ToString() != "")
{
int len = Convert.ToInt32(dr["CHARACTER_MAXIMUM_LENGTH"]);
if (len == -1 || len > 8000)
{
sql += "(MAX)";
}
else
{
sql += "(" + dr["CHARACTER_MAXIMUM_LENGTH"] + ")";
}
}
}
sql += ",\n";
}
sql = sql.TrimEnd(new[] { ',', '\n' }) + "\n";
// primary keys
if (table.PrimaryKey.Length > 0)
{
sql += "CONSTRAINT [PK_" + tableName + "] PRIMARY KEY CLUSTERED (";
sql = table.PrimaryKey.Aggregate(sql, (current, column) => current + ("[" + column.ColumnName + "],"));
sql = sql.TrimEnd(new[] { ',' }) + "))\n";
}
//if not ends with ")"
if ((table.PrimaryKey.Length == 0) && (!sql.EndsWith(")")))
{
sql += ")";
}
return sql;
}
using (var bulkCopy = new SqlBulkCopy(_conDest.ConnectionString))
{
bulkCopy.DestinationTableName = tblName;
bulkCopy.WriteToServer(_dtSource); //Source DataTable
}
//Get All Table Name List From Database
_query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment