Click here to Skip to main content
Licence CPOL
First Posted 31 Jul 2008
Views 13,104
Downloads 176
Bookmarked 50 times

Stored Procedure Generator

By | 31 Jul 2008 | Article
This software generates Insert, Update, Delete, and Select stored procedures (whichever you want) for selected tables.
 
Part of The SQL Zone sponsored by
See Also

SPGenerator.JPG

Introduction

StoredProcedureGenerator is a powerful tool to generate Insert, Update, Delete, and Select Stored Procedures (whichever you want) for selected tables for a particular database. You can connect to any SQL Server DB server.

Description

Select your DB server from the combo box. If you could not find your desired server, type it yourself. Check the radio-button to specify whether the DB server is on Windows Authentication or SQL Server Authentication. If it is SQL Server authentication, enter the username and password. You will be able to see all the databases on the selected database server. Select the desired database. You can test your connection by clicking Test Connection. Click the OK button. You would be able to see all the tables of the selected database in a grid. Check the tables for which you want to generate Stored Procedures. If you want this for all tables, select the checkbox on the top of the tables name (besides Name). Select the folder path where you want to save the script file. The system will give the name for the script file (StoredProcedures.sql).

Select which type of Stored Procedures you want (Insert, Update etc.). Click the OK button to generate the script file on the selected path. The system will give the names for the Stored Procedures itself according to the following format tablename_type (where type is Insert, Update etc). For example Person_Insert.

Using the Code

The following code generates the script files for creating Stored Procedures:

private void GenerateStoredProcedures()
{
    string sp = "";
    if (tablesDataGridView.Rows[0].Cells["Catalog"] != null)
    {
        sp = "USE " + tablesDataGridView.Rows[0].Cells["Catalog"].Value.ToString() +
            "\n";
        sp += "GO \n";
    }
    if (connection.State == ConnectionState.Closed)
    {
        connection.Open();
    }
    foreach (string item in spCheckedListBox.CheckedItems)
    {
        switch (item)
        {
        case "Insert":
            sp+=GenerateInsertStoredProcedure();
            break;
        case "Update":
            sp+=GenerateUpdateStoredProcedure();
            break;
        case "Delete":
            sp+=GenerateDeleteStoredProcedure();
            break;
        case "Select":
            sp+=GenerateSelectStoredProcedure();
            break;
        }
    }

    connection.Close();
    StreamWriter writer = new StreamWriter(filePathTextBox.Text +
        "\\StoredProcedures.sql");
    writer.Write(sp);
    writer.Close();
}
private string GenerateInsertStoredProcedure()
{ 
    string sp = ""; 
    foreach (DataGridViewRow tableRow in tablesDataGridView.Rows)
    {
        if (tableRow.Cells["IsSelected"].Value != null)
        {
            if ((bool)tableRow.Cells["IsSelected"].Value == true)
            {
                SqlCommand command = new SqlCommand("sp_columns", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value =
                    tableRow.Cells["TableName"].Value.ToString();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds);
                string spName = "[" + tableRow.Cells["Schema"].Value.ToString() + "].[" +
                    tableRow.Cells["TableName"].Value.ToString() + "_Insert]";
                sp = sp + "if exists (select * from dbo.sysobjects where id =
                     object_id(N'" + spName + "') and OBJECTPROPERTY(id,
                     N'IsProcedure') = 1) DROP PROCEDURE " + spName + "\n";
                sp = sp + "GO \n";
                sp = sp + "CREATE PROCEDURE " + spName + "\n";
                string columnNames = "";
                string parameters = "";
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (row["TYPE_NAME"].ToString() != "int identity")
                    {
                        string nullable = "";
                        if (row["NULLABLE"].ToString() == "1")
                        {
                            nullable = "=null";
                        }
                        sp = sp + "@" + row["COLUMN_NAME"].ToString() + " " +
                            row["TYPE_NAME"].ToString() + nullable + ","; 
                        columnNames = columnNames + "[" + row["COLUMN_NAME"].ToString() +
                            "],"; 
                        parameters = parameters + "@" +
                            row["COLUMN_NAME"].ToString() + ",";

                    }
                }
                sp = sp.Substring(0, sp.Length - 1);
                columnNames = columnNames.Substring(0, columnNames.Length - 1);
                parameters = parameters.Substring(0, parameters.Length - 1);
                sp = sp + "\n AS \n INSERT INTO " +
                    tableRow.Cells["TableName"].Value.ToString() +
                    "(" + columnNames + ") VALUES(" + parameters + ")\n";
                sp = sp + "GO \n";

            }
        }
    } 
    return sp;

}
private string GenerateUpdateStoredProcedure()
{

    string sp = ""; 
    foreach (DataGridViewRow tableRow in tablesDataGridView.Rows)
    {
        if (tableRow.Cells["IsSelected"].Value != null)
        {
            if ((bool)tableRow.Cells["IsSelected"].Value == true)
            {
                SqlCommand command = new SqlCommand("sp_columns", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value =
                     tableRow.Cells["TableName"].Value.ToString();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds);
                string spName = "[" + tableRow.Cells["Schema"].Value.ToString() + "].[" +
                    tableRow.Cells["TableName"].Value.ToString() + "_UpdateById]";
                sp = sp + "if exists (select * from dbo.sysobjects where id =
                    object_id(N'" + spName + "') and OBJECTPROPERTY(id,
                    N'IsProcedure') = 1) DROP PROCEDURE " + spName + "\n";
                sp = sp + "GO \n";
                sp = sp + "CREATE PROCEDURE " + spName + "\n";
                string columnNames = ""; 
                string identityColumn = "";
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string dataType = row["TYPE_NAME"].ToString();
                    if (dataType == "int identity")
                    {
                        identityColumn = row["COLUMN_NAME"].ToString();
                        dataType = "int";
                    }
                    else
                    {
                        columnNames = columnNames + "[" + row["COLUMN_NAME"].ToString() +
                            "]=@" + row["COLUMN_NAME"].ToString() + ",";
                    }
                    string nullable = "";
                    if (row["NULLABLE"].ToString() == "1")
                    {
                        nullable = "=null";
                    }
                    sp = sp + "@" + row["COLUMN_NAME"].ToString() + " " + dataType +
                        nullable + ","; 

                }
                sp = sp.Substring(0, sp.Length - 1);
                columnNames = columnNames.Substring(0, columnNames.Length - 1); 
                sp = sp + "\n AS \n UPDATE " +
                    tableRow.Cells["TableName"].Value.ToString() + " SET " +
                    columnNames + " WHERE [" + identityColumn + "]=@" +
                    identityColumn + "\n";
                sp = sp + "GO \n";
            }
        }
    }

    return sp;
}
private string GenerateDeleteStoredProcedure()
{
    string sp = "";
    foreach (DataGridViewRow tableRow in tablesDataGridView.Rows)
    {
        if (tableRow.Cells["IsSelected"].Value != null)
        {
            if ((bool)tableRow.Cells["IsSelected"].Value == true)
            {
                SqlCommand command = new SqlCommand("sp_columns", connection);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value =
                    tableRow.Cells["TableName"].Value.ToString();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds);
                string spName = "[" + tableRow.Cells["Schema"].Value.ToString() + "].[" +
                     tableRow.Cells["TableName"].Value.ToString() + "_DeleteById]";
                sp = sp + "if exists (select * from dbo.sysobjects where id =
                    object_id(N'" + spName + "') and OBJECTPROPERTY(id,
                    N'IsProcedure') = 1) DROP PROCEDURE " + spName + "\n";
                sp = sp + "GO \n";
                sp = sp + "CREATE PROCEDURE " + spName + "\n";

                string identityColumn = "";
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string dataType = row["TYPE_NAME"].ToString();
                    if (dataType == "int identity")
                    {
                        identityColumn = row["COLUMN_NAME"].ToString();
                        dataType = "int";
                        sp += "@" + identityColumn + " " + dataType + "\n";
                    } 
                } 
                sp = sp + "\n AS \n DELETE FROM " +
                    tableRow.Cells["TableName"].Value.ToString() + " WHERE [" +
                    identityColumn + "]=@" + identityColumn + "\n";
                sp = sp + "GO \n";
            }
        }
    }

    return sp;
}
private string GenerateSelectStoredProcedure()
{
    string sp = "";
    foreach (DataGridViewRow tableRow in tablesDataGridView.Rows)
    {
        if (tableRow.Cells["IsSelected"].Value != null)
        {
            if ((bool)tableRow.Cells["IsSelected"].Value == true)
            {
                SqlCommand command = new SqlCommand("sp_columns", connection);

                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@table_name", SqlDbType.NVarChar).Value =
                     tableRow.Cells["TableName"].Value.ToString();
                DataSet ds = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(command);
                da.Fill(ds);
                string spName = "[" + tableRow.Cells["Schema"].Value.ToString() + "].[" +
                     tableRow.Cells["TableName"].Value.ToString() + "_SelectAll]";
                sp = sp + "if exists (select * from dbo.sysobjects where id =
                    object_id(N'" + spName + "') and OBJECTPROPERTY(id,
                    N'IsProcedure') = 1) DROP PROCEDURE " + spName + "\n";
                sp = sp + "GO \n";
                sp = sp + "CREATE PROCEDURE " + spName + "\n";
                sp += "AS \n SELECT * FROM " +
                    tableRow.Cells["TableName"].Value.ToString() + "\n";
                sp += "GO \n";
                spName = "[" + tableRow.Cells["Schema"].Value.ToString() + "].[" +
                    tableRow.Cells["TableName"].Value.ToString() + "_SelectById]";
                sp = sp + "if exists (select * from dbo.sysobjects where id =
                    object_id(N'" + spName + "') and OBJECTPROPERTY(id,
                    N'IsProcedure') = 1) DROP PROCEDURE " + spName + "\n";
                sp = sp + "GO \n";
                sp = sp + "CREATE PROCEDURE " + spName + "\n";
                string identityColumn = "";
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string dataType = row["TYPE_NAME"].ToString();
                    if (dataType == "int identity")
                    {
                        identityColumn = row["COLUMN_NAME"].ToString();
                        dataType = "int";
                        sp += "@" + identityColumn + " " + dataType + "\n";
                    }
                }
                sp = sp + "\n AS \n SELECT * FROM " +
                    tableRow.Cells["TableName"].Value.ToString() +
                    " WHERE [" + identityColumn + "]=@" + identityColumn + "\n";
                sp = sp + "GO \n";
            }
        }
    }

    return sp;
}

Future Enhancements

I have plans to make it more generic so that it can generate Stored Procedures for other databases.

License

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

About the Author

Haider Ali Khan

Software Developer (Senior)
Talented Earth Organization (TEO) Pvt Ltd
Pakistan Pakistan

Member

I am working as a Senior Software Engineer in TEO (Pvt) Ltd Islamabad. I have more than four years of development experience. I have worked on many projects windows as well as web.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralNice Article Pinmemberirshadmohideen22:09 7 Aug '08  
GeneralMaking it Generic Pinmembermarkanthonygohara0:59 6 Aug '08  
Look at using Information_Schema it is used by all sql-92 compliant databases. Also if use Select * from Sysobjects for sql 2005 better info for what you are doing. Overall good job.
GeneralNice Work PinmemberShakeel Iqbal19:04 31 Jul '08  
GeneralGreat Work Done Pinmemberi_islamian18:56 31 Jul '08  
GeneralGreat Job Pinmembernomiikram18:54 31 Jul '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120604.1 | Last Updated 31 Jul 2008
Article Copyright 2008 by Haider Ali Khan
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid