While starting to code for any new application we are required to write POCO (Plain Old CLR Objects) classes for our database tables as Models (if you are using any ORM for data access) and we also need the stored procedures for our database tables. The process is simple but most of time repetitive and just like other developers I try to avoid it, so I wrote this simple windows forms application which helps me create database tables of POCO/model classes, base repository and related repository classes for the database tables in order to use Dapper ORM framework (which I mostly use in my web applications) and basic stored procedures scripts (like insert, update, delete etc) for the selected database tables. This saves time and helps me to avoid writing repetitive code.
This application is primarily targeting databases designed in SQL Server.
This is how the application looks:

Let's look into the code of the application and how it works. The flow of the application can be understood by the following diagram:

As you can see from the diagram, the first event occurs when the application is started and user clicks on ‘Get Database List’ button after entering the DB server connection string. The code of that event is as follows:
- private void btnGetDBList_Click(object sender, EventArgs e)
- {
- String conxString = txtConnectionString.Text.Trim();
- using (var sqlConx = new SqlConnection(conxString))
- {
- sqlConx.Open();
- var tblDatabases = sqlConx.GetSchema("Databases");
- sqlConx.Close();
- foreach (DataRow row in tblDatabases.Rows)
- {
- cboDatabases.Items.Add(row["database_name"]);
- }
- }
- cboDatabases.Items.Add("Select Database");
- cboDatabases.SelectedIndex = cboDatabases.Items.Count - 1;
- }
On the selection of database from dropdown application will fire ‘cboDatabases_SelectedIndexChanged’ event to get the tables list from the database and show it in the application checkbox list like following Image.

The source code of the dropdown selected index change event is as follows:
- private void cboDatabases_SelectedIndexChanged(object sender, EventArgs e)
- {
- try
- {
- if (cboDatabases.Text.Trim() != "Select Database")
- {
- //if ((cboCustomerName.SelectedValue.ToString().Trim() != "System.Data.DataRowView"))
- mSSqlDatabase = cboDatabases.Text.Trim();
- string strConn = txtConnectionString.Text.Trim() + ";Initial Catalog=" + mSSqlDatabase;
- SqlConnection cbConnection = null;
- try
- {
- DataTable dtSchemaTable = new DataTable("Tables");
- using (cbConnection = new SqlConnection(strConn))
- {
- SqlCommand cmdCommand = cbConnection.CreateCommand();
- cmdCommand.CommandText = "select table_name as Name from INFORMATION_SCHEMA.Tables where TABLE_TYPE ='BASE TABLE'";
- cbConnection.Open();
- dtSchemaTable.Load(cmdCommand.ExecuteReader(CommandBehavior.CloseConnection));
- }
- cblTableList.Items.Clear();
- for (int iCount = 0; iCount < dtSchemaTable.Rows.Count; iCount++)
- { f
- cblTableList.Items.Add(dtSchemaTable.Rows[iCount][0].ToString());
- }
- }
- finally
- {
- // ReSharper disable once PossibleNullReferenceException
- cbConnection.Close();
- }
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
} - }
- private void btnGenSQL_Click(object sender, EventArgs e)
- {
- try
- {
- GenerateSQLScripts();
- MessageBox.Show("SQL file(s) created Successfully at path mentioned in 'SQL Query Files'", "Success");
- grpOutPut.Visible = true;
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error : " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void GenerateSQLScripts()
- {
- string sFolderPath = CreateOutputDir(txtNamespace.Text.Trim() != "" ? txtNamespace.Text.Trim() : mSSqlDatabase);
- var objTableNames = new ArrayList();
- string sConString = txtConnectionString.Text + ";Initial Catalog=" + mSSqlDatabase;
- for (int iTableCount = 0; iTableCount < cblTableList.CheckedItems.Count; iTableCount++)
- {
- objTableNames.Add(cblTableList.CheckedItems[iTableCount].ToString());
- }
- txtQueryFilePath.Text = SqlScriptGenerator.GenerateSQLFiles(sFolderPath, sConString, txtgrantUser.Text.Trim(), txtSPPrefix.Text.Trim(), cbxMultipleFiles.Checked, objTableNames);
- }
- private string CreateOutputDir(string aSDirName)
- {
- string sRootDirPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + aSDirName;
- if (!Directory.Exists(sRootDirPath)) Directory.CreateDirectory(sRootDirPath);
- return sRootDirPath;
- }
The code of ‘GenerateSQLFiles’ method of ‘SqlScriptGenerator’ is as follows:
- public static string GenerateSQLFiles(string outputDirectory, string connectionString, string grantLoginName, string storedProcedurePrefix, bool createMultipleFiles, ArrayList tableNames)
- {
- string databaseName = "";
- string sqlPath;
- sqlPath = Path.Combine(outputDirectory, "SQL");
- List
- <Table> tableList = AppUtility.GetTableList(connectionString, outputDirectory, tableNames, ref databaseName);
- // Generate the necessary SQL for each table
- int count = 0;
- if (tableList.Count > 0)
- {
- // Create the necessary directories
- AppUtility.CreateSubDirectory(sqlPath, true);
- // Create the necessary database logins
- CreateUserQueries(databaseName, grantLoginName, sqlPath, createMultipleFiles);
- // Create the CRUD stored procedures and data access code for each table
- foreach (Table table in tableList)
- {
- CreateInsertStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateUpdateStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateDeleteStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateDeleteAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateSelectStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateSelectAllStoredProcedure(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- CreateSelectAllByStoredProcedures(table, grantLoginName, storedProcedurePrefix, sqlPath, createMultipleFiles);
- count++;
- }
- }
- return sqlPath;
- }
- internal static void CreateInsertStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- // Create the stored procedure name
- string procedureName = storedProcedurePrefix + table.Name + "Insert";
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- if (column.IsIdentity == false && column.IsRowGuidCol == false)
- {
- writer.Write("\t" + AppUtility.CreateParameterString(column, true));
- if (i < (table.Columns.Count - 1))
- {
- writer.Write(",");
- }
- writer.WriteLine();
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- // Initialize all RowGuidCol columns
- foreach (Column column in table.Columns)
- {
- if (column.IsRowGuidCol)
- {
- writer.WriteLine("SET @" + column.Name + " = NEWID()");
- writer.WriteLine();
- break;
- }
- }
- writer.WriteLine("INSERT INTO [" + table.Name + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- // Ignore any identity columns
- if (column.IsIdentity == false)
- {
- // Append the column name as a parameter of the insert statement
- if (i < (table.Columns.Count - 1))
- {
- writer.WriteLine("\t[" + column.Name + "],");
- }
- else
- {
- writer.WriteLine("\t[" + column.Name + "]");
- }
- }
- }
- writer.WriteLine(")");
- writer.WriteLine("VALUES");
- writer.WriteLine("(");
- // Create the values list
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- // Is the current column an identity column?
- if (column.IsIdentity == false)
- {
- // Append the necessary line breaks and commas
- if (i < (table.Columns.Count - 1)) { writer.WriteLine("\t@" + column.Name + ","); } else { writer.WriteLine("\t@" + column.Name); } } } writer.WriteLine(")"); // Should we include a line for returning the identity? foreach (Column column in table.Columns) { // Is the current column an identity column? if (column.IsIdentity) { writer.WriteLine(); writer.WriteLine("SELECT SCOPE_IDENTITY()"); break; } if (column.IsRowGuidCol) { writer.WriteLine(); writer.WriteLine("SELECT @" + column.Name); break; } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- ///
- <summary>
- /// Creates an update stored procedure SQL script for the specified table
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateUpdateStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- if (table.PrimaryKeys.Count > 0 && table.Columns.Count != table.PrimaryKeys.Count && table.Columns.Count != table.ForeignKeys.Count)
- {
- // Create the stored procedure name
- string procedureName = storedProcedurePrefix + table.Name + "Update";
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- if (i == 0)
- {
- }
- if (i < (table.Columns.Count - 1))
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
- }
- else
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.WriteLine("UPDATE [" + table.Name + "]");
- writer.Write("SET");
- // Create the set statement
- bool firstLine = true;
- for (int i = 0; i < table.Columns.Count; i++)
- {
- var column = table.Columns[i];
- // Ignore Identity and RowGuidCol columns
- if (table.PrimaryKeys.Contains(column) == false)
- {
- if (firstLine)
- {
- writer.Write(" ");
- firstLine = false;
- }
- else
- {
- writer.Write("\t");
- }
- writer.Write("[" + column.Name + "] = @" + column.Name);
- if (i < (table.Columns.Count - 1))
- {
- writer.Write(",");
- }
- writer.WriteLine();
- }
- }
- writer.Write("WHERE");
- // Create the where clause
- for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.Write(" [" + column.Name + "] = @" + column.Name); } else { writer.Write("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine(); writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }
- ///
- <summary>
- /// Creates an delete stored procedure SQL script for the specified table
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateDeleteStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- if (table.PrimaryKeys.Count > 0)
- {
- // Create the stored procedure name
- string procedureName = storedProcedurePrefix + table.Name + "Delete";
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < table.PrimaryKeys.Count; i++)
- {
- Column column = table.PrimaryKeys[i];
- if (i < (table.PrimaryKeys.Count - 1))
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
- }
- else
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.WriteLine("DELETE FROM [" + table.Name + "]");
- writer.Write("WHERE");
- // Create the where clause
- for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }
- ///
- <summary>
- /// Creates one or more delete stored procedures SQL script for the specified table and its foreign keys
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateDeleteAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- // Create a stored procedure for each foreign key
- foreach (List<Column> compositeKeyList in table.ForeignKeys.Values)
- {
- // Create the stored procedure name
- StringBuilder stringBuilder = new StringBuilder(255);
- stringBuilder.Append(storedProcedurePrefix + table.Name + "DeleteAllBy");
- // Create the parameter list
- for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i > 0)
- {
- stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name));
- }
- else
- {
- stringBuilder.Append(AppUtility.FormatPascal(column.Name));
- }
- }
- string procedureName = stringBuilder.ToString();
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < compositeKeyList.Count; i++)
- {
- Column column = compositeKeyList[i];
- if (i < (compositeKeyList.Count - 1))
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
- }
- else
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.WriteLine("DELETE FROM [" + table.Name + "]");
- writer.Write("WHERE");
- // Create the where clause
- for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }
- ///
- <summary>
- /// Creates an select stored procedure SQL script for the specified table
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateSelectStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count)
- {
- // Create the stored procedure name
- string procedureName = storedProcedurePrefix + table.Name + "Select";
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < table.PrimaryKeys.Count; i++)
- {
- Column column = table.PrimaryKeys[i];
- if (i == (table.PrimaryKeys.Count - 1))
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
- }
- else
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.Write("SELECT");
- // Create the list of columns
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- if (i == 0)
- {
- writer.Write(" ");
- }
- else
- {
- writer.Write("\t");
- }
- writer.Write("[" + column.Name + "]");
- if (i < (table.Columns.Count - 1))
- {
- writer.Write(",");
- }
- writer.WriteLine();
- }
- writer.WriteLine("FROM [" + table.Name + "]");
- writer.Write("WHERE");
- // Create the where clause
- for (int i = 0; i < table.PrimaryKeys.Count; i++) { Column column = table.PrimaryKeys[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }
- ///
- <summary>
- /// Creates an select all stored procedure SQL script for the specified table
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateSelectAllStoredProcedure(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- if (table.PrimaryKeys.Count > 0 && table.ForeignKeys.Count != table.Columns.Count)
- {
- // Create the stored procedure name
- string procedureName = storedProcedurePrefix + table.Name + "SelectAll";
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.Write("SELECT");
- // Create the list of columns
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- if (i == 0)
- {
- writer.Write(" ");
- }
- else
- {
- writer.Write("\t");
- }
- writer.Write("[" + column.Name + "]");
- if (i < (table.Columns.Count - 1)) { writer.Write(","); } writer.WriteLine(); } writer.WriteLine("FROM [" + table.Name + "]"); writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }
- ///
- <summary>
- /// Creates one or more select stored procedures SQL script for the specified table and its foreign keys
- /// </summary>
- /// <param name="table">Instance of the Table class that represents the table this stored procedure will be created for.</param>
- /// <param name="grantLoginName">Name of the SQL Server user that should have execute rights on the stored procedure.</param>
- /// <param name="storedProcedurePrefix">Prefix to be appended to the name of the stored procedure.</param>
- /// <param name="path">Path where the stored procedure script should be created.</param>
- /// <param name="createMultipleFiles">Indicates the procedure(s) generated should be created in its own file.</param>
- internal static void CreateSelectAllByStoredProcedures(Table table, string grantLoginName, string storedProcedurePrefix, string path, bool createMultipleFiles)
- {
- // Create a stored procedure for each foreign key
- foreach (List<Column> compositeKeyList in table.ForeignKeys.Values)
- {
- // Create the stored procedure name
- StringBuilder stringBuilder = new StringBuilder(255);
- stringBuilder.Append(storedProcedurePrefix + table.Name + "SelectAllBy");
- // Create the parameter list
- for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i > 0)
- {
- stringBuilder.Append("_" + AppUtility.FormatPascal(column.Name));
- }
- else
- {
- stringBuilder.Append(AppUtility.FormatPascal(column.Name));
- }
- }
- string procedureName = stringBuilder.ToString();
- string fileName;
- // Determine the file name to be used
- if (createMultipleFiles)
- {
- fileName = Path.Combine(path, procedureName + ".sql");
- }
- else
- {
- fileName = Path.Combine(path, "StoredProcedures.sql");
- }
- using (StreamWriter writer = new StreamWriter(fileName, true))
- {
- // Create the seperator
- if (createMultipleFiles == false)
- {
- writer.WriteLine();
- writer.WriteLine("/******************************************************************************");
- writer.WriteLine("******************************************************************************/");
- }
- // Create the drop statment
- writer.WriteLine("if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[" + procedureName + "]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)");
- writer.WriteLine("\tdrop procedure [dbo].[" + procedureName + "]");
- writer.WriteLine("GO");
- writer.WriteLine();
- // Create the SQL for the stored procedure
- writer.WriteLine("CREATE PROCEDURE [dbo].[" + procedureName + "]");
- writer.WriteLine("(");
- // Create the parameter list
- for (int i = 0; i < compositeKeyList.Count; i++)
- {
- Column column = compositeKeyList[i];
- if (i < (compositeKeyList.Count - 1))
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false) + ",");
- }
- else
- {
- writer.WriteLine("\t" + AppUtility.CreateParameterString(column, false));
- }
- }
- writer.WriteLine(")");
- writer.WriteLine();
- writer.WriteLine("AS");
- writer.WriteLine();
- writer.WriteLine("SET NOCOUNT ON");
- writer.WriteLine();
- writer.Write("SELECT");
- // Create the list of columns
- for (int i = 0; i < table.Columns.Count; i++)
- {
- Column column = table.Columns[i];
- if (i == 0)
- {
- writer.Write(" ");
- }
- else
- {
- writer.Write("\t");
- }
- writer.Write("[" + column.Name + "]");
- if (i < (table.Columns.Count - 1))
- {
- writer.Write(",");
- }
- writer.WriteLine();
- }
- writer.WriteLine("FROM [" + table.Name + "]");
- writer.Write("WHERE");
- // Create the where clause
- for (int i = 0; i < compositeKeyList.Count; i++) { Column column = compositeKeyList[i]; if (i == 0) { writer.WriteLine(" [" + column.Name + "] = @" + column.Name); } else { writer.WriteLine("\tAND [" + column.Name + "] = @" + column.Name); } } writer.WriteLine("GO"); // Create the grant statement, if a user was specified if (grantLoginName.Length > 0)
- {
- writer.WriteLine();
- writer.WriteLine("GRANT EXECUTE ON [dbo].[" + procedureName + "] TO [" + grantLoginName + "]");
- writer.WriteLine("GO");
- }
- }
- }
- }


Rodrigo RatanPosted Nov 4, 2019, 7:26 AM
Nice tool but it didn't generate all the code for delete actions
S.Ravi KumarPosted Apr 6, 2016, 1:55 AM
Thanks Guys
Vignesh ManiPosted Apr 5, 2016, 8:24 AM
nice one
Nitesh KejriwalPosted Apr 4, 2016, 8:15 AM
A nice article!
Humayun Kabir MamunPosted Apr 4, 2016, 5:00 AM
Nice...
Debasis SahaPosted Apr 4, 2016, 4:03 AM
Good One..
Rahul Kumar SaxenaPosted Apr 4, 2016, 3:47 AM
Good Show
Ankur MistryPosted Apr 4, 2016, 1:24 AM
nice share
janaPosted Apr 4, 2016, 12:37 AM
I found URL to download https://github.com/srkrathore/PocoSqlGenerator its working awesome thank u....
janaPosted Apr 4, 2016, 12:22 AM
Can please provide Link for download