Click here to Skip to main content
5,788,961 members and growing! (20,159 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate License: The Code Project Open License (CPOL)

Stored Procedure Generator

By Haider Ali Khan

This software generates Insert, Update, Delete, and Select stored procedures (whichever you want) for selected tables.
C#, SQL Server, ADO.NET, Dev

Posted: 31 Jul 2008
Updated: 31 Jul 2008
Views: 4,677
Bookmarked: 34 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
6 votes for this Article.
Popularity: 3.11 Rating: 4.00 out of 5
0 votes, 0.0%
1
1 vote, 16.7%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
5 votes, 83.3%
5

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


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.
Occupation: Software Developer (Senior)
Company: Talented Earth Organization (TEO) Pvt Ltd
Location: Pakistan Pakistan

Other popular Database articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
GeneralNice Articlememberirshadmohideen23:09 7 Aug '08  
GeneralMaking it Genericmembermarkanthonygohara1:59 6 Aug '08  
GeneralNice WorkmemberShakeel Iqbal20:04 31 Jul '08  
GeneralGreat Work Donememberi_islamian19:56 31 Jul '08  
GeneralGreat Jobmembernomiikram19:54 31 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 31 Jul 2008
Editor: Smitha Vijayan
Copyright 2008 by Haider Ali Khan
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project