Click here to Skip to main content
15,892,804 members
Articles / Programming Languages / SQL

SQL Stored Procedure Generator

Rate me:
Please Sign up or sign in to vote.
4.58/5 (11 votes)
29 Dec 2009CPOL2 min read 58.3K   5K   65   17
A simple application to generate Stored Procedures for existing tables in a SQL Server database.

Image 1

Introduction

The beginning of any new project/application mostly starts with a database, some classes, and then the UI. One of the most boring/tedious elements to this is generating the Stored Procedures needed for simple CRUD operations, as well as the class that references the database with all its methods etc.

Background

I searched pretty far and wide for a simple and decent application that would take an existing table from a database and generate the most common Stored Procedures for me, as well as script out the C# code to call these procs. There weren't too many useful applications that worked for me (or actually worked!).

Using the Code

By iterating through a selected table's columns, we can generate the script as need be. By treating some columns differently (i.e., making them appear in a Where clause, or knowing they can't be updated), the scripting can become fairly intelligent. (See example in code samples below.)

Here, a picture is worth quite a few words. The picture above shows the operations of the application.

Shown below is some code which repeats itself in various ways throughout the app. It's a mixture of SqlClient and SqlSMO operations to interrogate a database and its tables/columns etc.

C#
//Code to iterate tables             
private ServerConnection serverConnection = null;

private void btnGo_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;
    lstTables.Items.Clear();
    SqlConnection objCn = new SqlConnection(sqlControl1.ConnectionString);
    serverConnection = new ServerConnection(objCn);
    Server server = new Server(serverConnection);
    TableCollection objTables = 
      server.Databases[sqlControl1.DatabaseName].Tables;

    foreach (Table objTable in objTables)
    {
        lstTables.Items.Add(objTable.Name);
    }
    this.Cursor = Cursors.Default;
}

//Snippet to show column iteration and generation of script.
if (chkSelect.Checked)
{
    strSQL = "CREATE PROCEDURE [GetAll" + 
                  strTableName + "] " + Environment.NewLine;
    strSQL += " As Select ";

    foreach (Column item in server.Databases[
               sqlControl1.DatabaseName].Tables[strTableName].Columns)
    {
        keyCount++;
        strSQL += "[" + item.Name.ToString() + "]";
        if (keyCount < server.Databases[
           sqlControl1.DatabaseName].Tables[strTableName].Columns.Count) 
           strSQL += "," + Environment.NewLine;
    }

    strSQL +=" from [" + strTableName + "]";
    txtSQL.Text += strSQL + Environment.NewLine + Environment.NewLine;
}

Below is a screenshot of a sample table, and the subsequent generated scripts.

Image 2

SQL
CREATE PROCEDURE [GetAllVariables] As Select [ID], 
  [VarName], [VarDesc], [VarType] from [Variables]
CREATE PROCEDURE [DeleteVariables] (@ID int) As Delete from [Variables] Where ID = @ID
CREATE PROCEDURE [AddVariables] (@VarName varchar, @VarDesc varchar, @VarType varchar) 
  As Insert Into [Variables] ( VarName, VarDesc, VarType) 
  Values ( @VarName, @VarDesc, @VarType) select SCOPE_IDENTITY()
CREATE PROCEDURE [UpdateVariables] (@ID int, @VarName varchar, 
  @VarDesc varchar, @VarType varchar) As Update [Variables] set 
  VarName = @VarName, VarDesc = @VarDesc, VarType = @VarType Where ID = @ID
CREATE PROCEDURE [AddUpdateVariables] (@ID int, @VarName varchar, @VarDesc varchar, 
  @VarType varchar) As Begin If (Select ID from [Variables] 
  Where ID = @ID) <> 0 Begin Update [Variables] set VarName = @VarName, 
  VarDesc = @VarDesc, VarType = @VarType Where ID = @ID End Else Begin Insert 
  Into [Variables] ( VarName, VarDesc, VarType) 
  Values ( @VarName, @VarDesc, @VarType) select SCOPE_IDENTITY() End End 

Points of Interest

Nothing too special here about this project, just some string manipulation and working with the SQL SMO objects.

Note: The "Save To File" button will save each script individually. Also, I include "select SCOPE_IDENTITY()" in my insert procedures, because that's something I use quite often.

History

This is the first iteration. The next one will be adding the ability to generate the classes and interfaces for a table.

License

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


Written By
Founder Jayess Software
South Africa South Africa
Jayess Software is a provider of both outsourced development resources, and developed solutions

Comments and Discussions

 
QuestionSP Gen using Tools4SQL.net Pin
Member 435095014-Feb-14 2:52
Member 435095014-Feb-14 2:52 
SuggestionSmall suggestion Pin
Member 978640120-Oct-13 6:25
Member 978640120-Oct-13 6:25 
QuestionGreat Pin
Member 920344323-Nov-12 23:05
Member 920344323-Nov-12 23:05 
SuggestionFail to save procedure Pin
Member 900291119-Jul-12 6:02
Member 900291119-Jul-12 6:02 
GeneralMy vote of 5 Pin
ESST22-Oct-10 18:42
ESST22-Oct-10 18:42 
GeneralNice article Pin
jkpieters4-Feb-10 1:26
jkpieters4-Feb-10 1:26 
GeneralMy vote of 2 Pin
Simon Hughes6-Jan-10 2:33
Simon Hughes6-Jan-10 2:33 
GeneralSmall suggession Pin
Vijay Bhasker Reddy CH4-Jan-10 22:21
Vijay Bhasker Reddy CH4-Jan-10 22:21 
RantRe: Small suggession Pin
MacSpudster5-Jan-10 11:34
professionalMacSpudster5-Jan-10 11:34 
GeneralOh NO!!! Pin
David Lean4-Jan-10 16:58
David Lean4-Jan-10 16:58 
GeneralRe: Oh NO!!! Pin
jkpieters4-Feb-10 1:22
jkpieters4-Feb-10 1:22 
QuestionRe: Oh NO!!! Pin
CrshTstDmmy11-Jan-11 7:50
CrshTstDmmy11-Jan-11 7:50 
QuestionSCOPE_IDENTITY??? Pin
Irasimus30-Dec-09 6:16
Irasimus30-Dec-09 6:16 
From your "Points of Interest" section: "Also, I include "select SCOPE_IDENTITY()" in my insert procedures, because that's something I use quite often."

SCOPE_IDENTITY should never be used in SQL Server to retrieve an identity value after an insert because it returns the last identity value inserted for any table within the current scope, and if you have triggers that insert records to other tables, you may or may not get the value you are expecting.

As a general rule, if you are attempting to return the newly assigned identity value after an insert, you should always use IDENT_CURRENT('Table Name'), and the command should be run immediatly after the insert command. Running any sql commands in between can cause you to get an incorrect identity value as well.

Other suggestions:

Include SET NOCOUNT ON at the beginning of every stored procedure.

Change "If (Select ID from [Variables] Where ID = @ID) <> 0" to "If exists (Select * from [Variables] Where ID = @ID)". This will generally give you a slight performance increase, and will prevent logic errors if @ID were a GUID rather than an Int.

Some may disagree with me on this point, but I believe a stored procedure should always return the same structure regardless of input parameters or execution paths, and all columns in your result set should have explicitly defined names. In your insert example, you are returning an unnamed column that contains an identity value when an insert occurs, but nothing if an update occurs. I modified one of your original examples below for reference.


CREATE PROCEDURE [AddUpdateVariables] (@ID int, @VarName varchar, @VarDesc varchar, @VarType varchar) As Begin set nocount on If exists (Select * from [Variables] Where ID = @ID) Begin Update [Variables] set VarName = @VarName, VarDesc = @VarDesc, VarType = @VarType Where ID = @ID select @ID as [IdentityValue] End Else Begin Insert Into [Variables] ( VarName, VarDesc, VarType) Values ( @VarName, @VarDesc, @VarType) select IDENT_CURRENT('Variables') as [IdentityValue] End End
AnswerRe: SCOPE_IDENTITY??? Pin
Mi.Chal.31-Dec-09 1:33
Mi.Chal.31-Dec-09 1:33 
GeneralRe: SCOPE_IDENTITY??? Pin
Irasimus6-Jan-10 10:31
Irasimus6-Jan-10 10:31 
GeneralVery Good Pin
Syed M Hussain30-Dec-09 2:48
Syed M Hussain30-Dec-09 2:48 
GeneralGood article Pin
ColinBud29-Dec-09 23:29
ColinBud29-Dec-09 23:29 

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

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