Click here to Skip to main content
15,896,063 members
Articles / Database Development / SQL Server

Build SQL Server Stored Procedures From Information_Schema Tables

Rate me:
Please Sign up or sign in to vote.
4.67/5 (10 votes)
5 Apr 2006CPOL4 min read 70.2K   756   51  
Save hours of time by creating stored procedures and code from database metadata.
using System;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;
using System.Windows.Forms;

namespace BuildCode {
	/// <summary>
	/// Summary description for frmBuildCode.
	/// </summary>
	public class frmBuildCode : System.Windows.Forms.Form {

		private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
		private string folderName = string.Empty;
		private string tableName = string.Empty;
		private string tableSchema = string.Empty;
		private string tableIdentityColumn = string.Empty;
		private string outputType = string.Empty;
		private CSharpClass csc = new CSharpClass();
		private SqlInsert sqli = new SqlInsert();
		private SqlUpdate sqlu = new SqlUpdate();
		private SqlDelete sqld = new SqlDelete();
		private SqlSelect sqls = new SqlSelect();
		private FromDataRow fdr = new FromDataRow();
		private SqlParms sqlp = new SqlParms();
		private ArrayList DbKeys = new ArrayList();
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.ComboBox cbxDatabases;
		private System.Windows.Forms.Button btnShowTables;
		private System.Windows.Forms.GroupBox groupBox2;
		private System.Windows.Forms.Button btnSelectOutputFolder;
		private System.Windows.Forms.Label lblOutputFolder;
		private System.Windows.Forms.Button btnBuildCode;
		private System.Windows.Forms.TextBox txtOutput;
		private System.Windows.Forms.Button btnCopyToClipboard;
		private System.Windows.Forms.ComboBox cbxTables;
		private System.Windows.Forms.Button btnOutputCode;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.RadioButton rbCSharpClass;
		private System.Windows.Forms.RadioButton rbSqlInsert;
		private System.Windows.Forms.RadioButton rbSqlUpdate;
		private System.Windows.Forms.RadioButton rbSqlDelete;
		private System.Windows.Forms.RadioButton rbSqlSelect;
		private System.Windows.Forms.RadioButton rbFromDataRow;
		private System.Windows.Forms.RadioButton rbSqlParms;
		private System.ComponentModel.Container components = null;

		public frmBuildCode() {
			InitializeComponent();
			cbxDatabases.DataSource = BuildKeyArrayList();
			cbxDatabases.ValueMember = "DbKey";
			cbxDatabases.DisplayMember = "DbKey";
		}

		private void btnBuildCode_Click(object sender, System.EventArgs e) {
			ArrayList al = new ArrayList();
			txtOutput.Text = "";
			try {
				if (cbxTables.SelectedValue != null) {
					if (cbxTables.SelectedValue.ToString().Length > 0) {
						tableName = cbxTables.SelectedValue.ToString();
						tableSchema = TableDAO.GetTableSchema(GetConnectionString(cbxDatabases.SelectedValue.ToString()), tableName);
						tableIdentityColumn = TableDAO.GetTableIdentityColumn(GetConnectionString(cbxDatabases.SelectedValue.ToString()), tableName);
						if (tableIdentityColumn.Length == 0) {
							tableIdentityColumn = "xxNoIdentityColumnxx";
						}
						al = ColumnDAO.GetColumns(GetConnectionString(cbxDatabases.SelectedValue.ToString()), tableName, tableSchema);
						if (al.Count > 0) {
							if (rbCSharpClass.Checked) {
								outputType = "CSharpClass";
								csc = new CSharpClass();
								csc.BuildCodeStartOfLoop(tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									csc.BuildCodeEachColumn(col);
								}
								csc.BuildCodeEndOfLoop(tableName);
								txtOutput.Text = csc.CodeOut;
							}
							if (rbSqlInsert.Checked) {
								outputType = "SqlInsert";
								sqli = new SqlInsert();
								sqli.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									sqli.BuildCodeEachColumn(col, tableIdentityColumn);
								}
								sqli.BuildCodeEndOfLoop(tableName, tableIdentityColumn);
								txtOutput.Text = sqli.CodeOut;
							}
							if (rbSqlUpdate.Checked) {
								outputType = "SqlUpdate";
								sqlu = new SqlUpdate();
								sqlu.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									sqlu.BuildCodeEachColumn(col, tableIdentityColumn);
								}
								sqlu.BuildCodeEndOfLoop(tableName, tableIdentityColumn);
								txtOutput.Text = sqlu.CodeOut;
							}
							if (rbSqlDelete.Checked) {
								outputType = "SqlDelete";
								sqld = new SqlDelete();
								sqld.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									sqld.BuildCodeEachColumn(col, tableIdentityColumn);
								}
								sqld.BuildCodeEndOfLoop(tableName, tableIdentityColumn);
								txtOutput.Text = sqld.CodeOut;
							}
							if (rbSqlSelect.Checked) {
								outputType = "SqlSelect";
								sqls = new SqlSelect();
								sqls.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									sqls.BuildCodeEachColumn(col, tableIdentityColumn);
								}
								sqls.BuildCodeEndOfLoop(tableName, tableIdentityColumn);
								txtOutput.Text = sqls.CodeOut;
							}
							if (rbFromDataRow.Checked) {
								outputType = "FromDataRow";
								fdr = new FromDataRow();
								fdr.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									fdr.BuildCodeEachColumn(col);
								}
								fdr.BuildCodeEndOfLoop(tableName);
								txtOutput.Text = fdr.CodeOut;
							}
							if (rbSqlParms.Checked) {
								outputType = "SqlParms";
								sqlp = new SqlParms();
								sqlp.BuildCodeStartOfLoop(tableSchema, tableName);
								IEnumerator rows = al.GetEnumerator();
								while (rows.MoveNext()) {
									Column col = (Column) rows.Current;
									sqlp.BuildCodeEachColumn(col);
								}
								sqlp.BuildCodeEndOfLoop(tableName);
								txtOutput.Text = sqlp.CodeOut;
							}
						}
					}
				} else {
					MessageBox.Show("Please select a table.");
				}
			}
			catch (Exception ex) {
				MessageBox.Show(ex.ToString());
			}
		}

		private void btnOutputCode_Click(object sender, System.EventArgs e) {
			try {
				if (folderName.Length > 0) {
					if (tableName.Length > 0) {
						if (txtOutput.Text.Length > 0) {
							PutCodeOut(folderName + @"\" + tableName + "_" + outputType, txtOutput.Text);
							MessageBox.Show("Code written.");
						} else {
							MessageBox.Show("There is no code to write.");
						}
					} else {
						MessageBox.Show("Please select a table.");
					}
				} else {
					MessageBox.Show("Please select an output folder.");
				}
			}
			catch (Exception ex) {
				MessageBox.Show(ex.ToString());
			}
		}

		private void btnShowTables_Click(object sender, System.EventArgs e) {
			try {
				frmBuildCode.ActiveForm.Cursor = Cursors.WaitCursor;
				cbxTables.DataSource = TableDAO.GetTables(GetConnectionString(cbxDatabases.SelectedValue.ToString()));
				cbxTables.ValueMember = "TableName";
				cbxTables.DisplayMember = "TableName";
				frmBuildCode.ActiveForm.Cursor = Cursors.Arrow;
			}
			catch (Exception ex) {
				MessageBox.Show(ex.ToString());
			}
		}

		private void btnSelectOutputFolder_Click(object sender, System.EventArgs e) {
			this.folderBrowserDialog1.Description = "Select the folder that you want to write output to.";
			this.folderBrowserDialog1.ShowNewFolderButton = true;
			this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
			DialogResult result = folderBrowserDialog1.ShowDialog();
			if (result == DialogResult.OK) {
				folderName = folderBrowserDialog1.SelectedPath;
				lblOutputFolder.Text = folderName;
			}
		}

		private void btnSelectAll_Click(object sender, System.EventArgs e) {
			txtOutput.SelectAll();
			txtOutput.Copy();
		}

		private string GetConnectionString(string key) {
			string connStr = string.Empty;
			try {
				connStr = ConfigurationSettings.AppSettings[key];
				//Encrypter encrypter = new Encrypter(Encrypter.Algorithm.Rijndael);
				//connStr = encrypter.Decrypt(connStr, "coDe%prOjeCt");
			}
			catch (Exception ex) {
				MessageBox.Show(ex.ToString());
			}
			return connStr;
		}

		private ArrayList BuildKeyArrayList() {
			NameValueCollection appSettings = ConfigurationSettings.AppSettings;
			IEnumerator appSettingsEnum = appSettings.Keys.GetEnumerator();
			int r = 0;
			while (appSettingsEnum.MoveNext()) {
				string key = appSettings.Keys[r];
				DbKeys.Add(new DataBase(r, appSettings.Keys[r], appSettings.GetValues(r)[0]));
				r++;
			}
			return DbKeys;
		}

		private void PutCodeOut(string fileName, string outCode) {
			try {
				using (StreamWriter sw = new StreamWriter(fileName + TimeStamp() + ".txt")) {
					sw.WriteLine(outCode);
				}
			}
			catch (Exception ex) {
				throw ex;
			}
		}

		private string TimeStamp() {
			string timeStampOut = string.Empty;
			DateTime now = System.DateTime.Now;
			string thisYear = now.Year.ToString();
			string thisMonth = now.Month.ToString().PadLeft(2, '0');
			string thisDay = now.Day.ToString().PadLeft(2, '0');
			string thisHour = now.Hour.ToString().PadLeft(2, '0');
			string thisMinute = now.Minute.ToString().PadLeft(2, '0');
			string thisSecond = now.Second.ToString().PadLeft(2, '0');
			timeStampOut = '_' + thisYear + thisMonth + thisDay + '_' + thisHour + thisMinute + thisSecond;
			return timeStampOut;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) {
			if( disposing ) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.cbxTables = new System.Windows.Forms.ComboBox();
			this.btnShowTables = new System.Windows.Forms.Button();
			this.cbxDatabases = new System.Windows.Forms.ComboBox();
			this.groupBox2 = new System.Windows.Forms.GroupBox();
			this.btnOutputCode = new System.Windows.Forms.Button();
			this.lblOutputFolder = new System.Windows.Forms.Label();
			this.btnSelectOutputFolder = new System.Windows.Forms.Button();
			this.btnBuildCode = new System.Windows.Forms.Button();
			this.txtOutput = new System.Windows.Forms.TextBox();
			this.btnCopyToClipboard = new System.Windows.Forms.Button();
			this.groupBox3 = new System.Windows.Forms.GroupBox();
			this.rbSqlParms = new System.Windows.Forms.RadioButton();
			this.rbFromDataRow = new System.Windows.Forms.RadioButton();
			this.rbSqlSelect = new System.Windows.Forms.RadioButton();
			this.rbSqlDelete = new System.Windows.Forms.RadioButton();
			this.rbSqlUpdate = new System.Windows.Forms.RadioButton();
			this.rbSqlInsert = new System.Windows.Forms.RadioButton();
			this.rbCSharpClass = new System.Windows.Forms.RadioButton();
			this.groupBox1.SuspendLayout();
			this.groupBox2.SuspendLayout();
			this.groupBox3.SuspendLayout();
			this.SuspendLayout();
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.cbxTables);
			this.groupBox1.Controls.Add(this.btnShowTables);
			this.groupBox1.Controls.Add(this.cbxDatabases);
			this.groupBox1.Location = new System.Drawing.Point(16, 16);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(608, 64);
			this.groupBox1.TabIndex = 5;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Source";
			// 
			// cbxTables
			// 
			this.cbxTables.Location = new System.Drawing.Point(312, 24);
			this.cbxTables.Name = "cbxTables";
			this.cbxTables.Size = new System.Drawing.Size(192, 21);
			this.cbxTables.TabIndex = 6;
			// 
			// btnShowTables
			// 
			this.btnShowTables.Location = new System.Drawing.Point(208, 24);
			this.btnShowTables.Name = "btnShowTables";
			this.btnShowTables.Size = new System.Drawing.Size(88, 23);
			this.btnShowTables.TabIndex = 5;
			this.btnShowTables.Text = "Show Tables";
			this.btnShowTables.Click += new System.EventHandler(this.btnShowTables_Click);
			// 
			// cbxDatabases
			// 
			this.cbxDatabases.Location = new System.Drawing.Point(8, 24);
			this.cbxDatabases.Name = "cbxDatabases";
			this.cbxDatabases.Size = new System.Drawing.Size(192, 21);
			this.cbxDatabases.TabIndex = 4;
			// 
			// groupBox2
			// 
			this.groupBox2.Controls.Add(this.btnOutputCode);
			this.groupBox2.Controls.Add(this.lblOutputFolder);
			this.groupBox2.Controls.Add(this.btnSelectOutputFolder);
			this.groupBox2.Location = new System.Drawing.Point(16, 488);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(608, 72);
			this.groupBox2.TabIndex = 6;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Put to File";
			// 
			// btnOutputCode
			// 
			this.btnOutputCode.Location = new System.Drawing.Point(512, 24);
			this.btnOutputCode.Name = "btnOutputCode";
			this.btnOutputCode.Size = new System.Drawing.Size(88, 23);
			this.btnOutputCode.TabIndex = 11;
			this.btnOutputCode.Text = "Output Code";
			this.btnOutputCode.Click += new System.EventHandler(this.btnOutputCode_Click);
			// 
			// lblOutputFolder
			// 
			this.lblOutputFolder.BackColor = System.Drawing.SystemColors.ControlLight;
			this.lblOutputFolder.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
			this.lblOutputFolder.Location = new System.Drawing.Point(144, 16);
			this.lblOutputFolder.Name = "lblOutputFolder";
			this.lblOutputFolder.Size = new System.Drawing.Size(352, 40);
			this.lblOutputFolder.TabIndex = 2;
			this.lblOutputFolder.Text = "[No output folder selected]";
			this.lblOutputFolder.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
			// 
			// btnSelectOutputFolder
			// 
			this.btnSelectOutputFolder.Location = new System.Drawing.Point(8, 24);
			this.btnSelectOutputFolder.Name = "btnSelectOutputFolder";
			this.btnSelectOutputFolder.Size = new System.Drawing.Size(128, 24);
			this.btnSelectOutputFolder.TabIndex = 1;
			this.btnSelectOutputFolder.Text = "Select Output Folder";
			this.btnSelectOutputFolder.Click += new System.EventHandler(this.btnSelectOutputFolder_Click);
			// 
			// btnBuildCode
			// 
			this.btnBuildCode.Location = new System.Drawing.Point(16, 144);
			this.btnBuildCode.Name = "btnBuildCode";
			this.btnBuildCode.Size = new System.Drawing.Size(88, 23);
			this.btnBuildCode.TabIndex = 8;
			this.btnBuildCode.Text = "Build Code";
			this.btnBuildCode.Click += new System.EventHandler(this.btnBuildCode_Click);
			// 
			// txtOutput
			// 
			this.txtOutput.Location = new System.Drawing.Point(16, 176);
			this.txtOutput.Multiline = true;
			this.txtOutput.Name = "txtOutput";
			this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.txtOutput.Size = new System.Drawing.Size(608, 304);
			this.txtOutput.TabIndex = 9;
			this.txtOutput.Text = "";
			// 
			// btnCopyToClipboard
			// 
			this.btnCopyToClipboard.Location = new System.Drawing.Point(496, 144);
			this.btnCopyToClipboard.Name = "btnCopyToClipboard";
			this.btnCopyToClipboard.Size = new System.Drawing.Size(128, 23);
			this.btnCopyToClipboard.TabIndex = 17;
			this.btnCopyToClipboard.Text = "Copy To Clipboard";
			this.btnCopyToClipboard.Click += new System.EventHandler(this.btnSelectAll_Click);
			// 
			// groupBox3
			// 
			this.groupBox3.Controls.Add(this.rbSqlParms);
			this.groupBox3.Controls.Add(this.rbFromDataRow);
			this.groupBox3.Controls.Add(this.rbSqlSelect);
			this.groupBox3.Controls.Add(this.rbSqlDelete);
			this.groupBox3.Controls.Add(this.rbSqlUpdate);
			this.groupBox3.Controls.Add(this.rbSqlInsert);
			this.groupBox3.Controls.Add(this.rbCSharpClass);
			this.groupBox3.Location = new System.Drawing.Point(16, 88);
			this.groupBox3.Name = "groupBox3";
			this.groupBox3.Size = new System.Drawing.Size(608, 48);
			this.groupBox3.TabIndex = 18;
			this.groupBox3.TabStop = false;
			this.groupBox3.Text = "Code to build";
			// 
			// rbSqlParms
			// 
			this.rbSqlParms.Location = new System.Drawing.Point(520, 16);
			this.rbSqlParms.Name = "rbSqlParms";
			this.rbSqlParms.Size = new System.Drawing.Size(84, 24);
			this.rbSqlParms.TabIndex = 28;
			this.rbSqlParms.Text = "SQL Parms";
			// 
			// rbFromDataRow
			// 
			this.rbFromDataRow.Location = new System.Drawing.Point(424, 16);
			this.rbFromDataRow.Name = "rbFromDataRow";
			this.rbFromDataRow.TabIndex = 27;
			this.rbFromDataRow.Text = "From DataRow";
			// 
			// rbSqlSelect
			// 
			this.rbSqlSelect.Location = new System.Drawing.Point(336, 16);
			this.rbSqlSelect.Name = "rbSqlSelect";
			this.rbSqlSelect.Size = new System.Drawing.Size(88, 24);
			this.rbSqlSelect.TabIndex = 26;
			this.rbSqlSelect.Text = "SQL Select";
			// 
			// rbSqlDelete
			// 
			this.rbSqlDelete.Location = new System.Drawing.Point(248, 16);
			this.rbSqlDelete.Name = "rbSqlDelete";
			this.rbSqlDelete.Size = new System.Drawing.Size(88, 24);
			this.rbSqlDelete.TabIndex = 25;
			this.rbSqlDelete.Text = "SQL Delete";
			// 
			// rbSqlUpdate
			// 
			this.rbSqlUpdate.Location = new System.Drawing.Point(160, 16);
			this.rbSqlUpdate.Name = "rbSqlUpdate";
			this.rbSqlUpdate.Size = new System.Drawing.Size(88, 24);
			this.rbSqlUpdate.TabIndex = 24;
			this.rbSqlUpdate.Text = "SQL Update";
			// 
			// rbSqlInsert
			// 
			this.rbSqlInsert.Location = new System.Drawing.Point(80, 16);
			this.rbSqlInsert.Name = "rbSqlInsert";
			this.rbSqlInsert.Size = new System.Drawing.Size(76, 24);
			this.rbSqlInsert.TabIndex = 23;
			this.rbSqlInsert.Text = "SQL Insert";
			// 
			// rbCSharpClass
			// 
			this.rbCSharpClass.Checked = true;
			this.rbCSharpClass.Location = new System.Drawing.Point(8, 16);
			this.rbCSharpClass.Name = "rbCSharpClass";
			this.rbCSharpClass.Size = new System.Drawing.Size(72, 24);
			this.rbCSharpClass.TabIndex = 22;
			this.rbCSharpClass.TabStop = true;
			this.rbCSharpClass.Text = "C# Class";
			// 
			// frmBuildCode
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(640, 574);
			this.Controls.Add(this.groupBox3);
			this.Controls.Add(this.btnCopyToClipboard);
			this.Controls.Add(this.txtOutput);
			this.Controls.Add(this.btnBuildCode);
			this.Controls.Add(this.groupBox2);
			this.Controls.Add(this.groupBox1);
			this.MaximizeBox = false;
			this.Name = "frmBuildCode";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Build Code";
			this.groupBox1.ResumeLayout(false);
			this.groupBox2.ResumeLayout(false);
			this.groupBox3.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() {
			Application.Run(new frmBuildCode());
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions