SQL Server Stored Procedures – Fundamentals

We are telling the database that we want to create a stored procedure that is called “usp_displayallusers” that is characterized by the code that follows. After the “AS” entry, you will simply enter SQL code as you would in a regularly query. For our first, we will use a SELECT statement:

SELECT * FROM USERLIST

Now, your stored procedure should look like this:

/*
Name:  usp_displayallusers
Description:  displays all records and columns in USERLIST table
Author:  Tom O’Neill
Modification Log: Change

Description                  Date         Changed By
Created procedure            7/15/2003    Tom O’Neill
*/

CREATE PROCEDURE usp_displayallusers

AS

SELECT * FROM USERLIST

Congratulations, you have written your first stored procedure. If you authored the procedure in a text editor, now would be a good time to copy it into the New Stored Procedure window in SQL Server. Once you have done so, click the “Check Syntax” box. This is a great troubleshooting tool for beginners and experts alike. When SQL Server tells you “Syntax check successful!”, you can click OK to save your stored procedure. To view the procedure, simply double-click usp_displayallusers in the Stored Procedures window. To run your stored procedure, open the Query Analyzer and type:

exec usp_displayallusers

Then, click the green “play” button to run the query. You will see that the procedure has run successfully.

It can be frustrating to start from scratch. Right now, you can think of all the things you want to accomplish with stored procedures; you just need to learn how! That will happen next. Let’s take a look at some more useful stored procedures.

More Sophisticated Stored Procedures

In this section, we are going to address a few new topics. In addition to writing SELECT queries, you are going to want to insert, update, and delete database records. Also, you will probably want to pass information from outside the query. Since inserts and updates require some sort of data input to be useful, our first topic will be variables. From there, we will use data stored in variables for inserts and updates.

Note: In this article, we will only address input variables (variables that pass data to the SQL statement in the stored procedure). There are various types of outputs and returns, and they can become quite complex. Since this article is an introduction, we will leave outputs for another time.

Input Variables

There are many reasons for wanting to pass data to a stored procedure, especially if your stored procedure is being called by a dynamic web page or other application. You may want to use a SELECT statement to pull information into the application for dynamic display. In this case, you would pass selection criteria to the stored procedure (for use in a WHERE clause). If you are inserting new records, you will need to get the data from somewhere. Updating existing records also involves simply getting the data. In both INSERT and UPDATE statements, it is necessary to pass data to the stored procedure. For INSERT, UPDATE, and SELECT statements (to name a few), you can pass the data to your stored procedure using variables.

Input variables are essentially “storage” for data that you want to pass to your stored procedure. Inside your stored procedure, you will declare variables at the top of the stored procedure. How does the data get there? The data is entered in the exec statement that you use to kick off the stored procedure. We’ll discuss that in more detail in a bit.

There are two types of variables that you can create in SQL Server stored procedures:  Global and Local. Since this is for beginners, I don’t want to go crazy with too many options. We’ll stick to local variables for now. You can name a variable most anything you want, though it is best to stick with meaningful works and abbreviations. I also tend to avoid punctuation, though underscores (“_”) are sometimes helpful. The only real requirement is that you begin your variable with the “@” symbol. Here are some examples:

  • @f_name

  • @fullname

  • @HomePhone

  • @ext

For every data element you want to pass, you will need to declare a variable. Declaring a variable is quite easy. You decide on a name and a datatype (integer, text, etc.), and indicate the name and datatype at the top of the procedure (below the “CREATE PROCEDURE” line). Let’s add a record to USERLIST. Remember the following:

  • “usr_id” is the primary key, and is system-generated. We won’t need to pass a value for it.

  • “login”, “pswd”, “l_name”, and “email” are required fields. We will have to pass values for them.

Continues…



Related Articles :

  • No Related Articles Found

9 Responses to “SQL Server Stored Procedures – Fundamentals”

  1. creating and calling stored procedure in .net:

    create procedure insert1(@userid int,@username varchar(50))
    as
    begin
    insert into emp(id,name)values(@userid,@username)
    end

    NOTE:(id,name) are the columns of table in which you want to insert data.

    CALLING STORED PROCEDURE :

    initialize this globally:
    public partial class1:class
    {
    sqlconnection con;
    sqlcommand cmd;
    }

    on page_load(): // write on page load()
    {
    con=new sqlconnection(“Connection string”);
    cmd=new sqlcommand();
    cmd.connection=con;
    cmd.commandtype=commandtype.stored procedure;
    }

    on button_click() // write on insert button_clik event

    {
    cmd.parameters.clear();
    cmd.commandtext=”insert1″;
    // stored procedure name just created.
    cmd.parameters.addwithvalue(“@userid”,textbox1.text);

    cmd.parameters.addwithvalue(“@username”,textbox2.text);
    con.open();
    cmd.executenonquery();
    messagebox.show(“stored procedure inserted…”);
    con.close();
    }

  2. Hi Tom,

    I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of stored procedure and it will help me a lot.

    Thank you very much!
    Bhuvan

  3. Hi Tom
    Your article are really awesome.actually i was in search for some good articles on stored procedures and finally i got one.
    The most important is the simplicity which will be very helpful for the beginners.

    Thanks
    Avinash

  4. Hi Tom,

    This was a really informative article for us beginner SQL developers. The procedure was not very complex and easy to understand. I have been studying from a high level SQL developer in order to understand SQL better and he very much confused me with the very advanced code that he was using. Example of more complex code

    /*
    declare @today datetime
    SET @Today = getdate()
    EXECUTE sproc_insertvendor @name = ‘something Else’, @countofpayments = 3, @lastpaydate = @Today, @nextpaydate = @Today, @Comments = null
    */

    IF EXISTS (SELECT * FROM SYSOBJECTS WHERE Name = ‘sproc_insertvendor’)
    DROP PROCEDURE sproc_insertvendor
    GO

    CREATE PROCEDURE sproc_insertvendor
    @name varchar(200),
    @countOfPayments int,
    @LastPayDate datetime,
    @nextpaydate datetime,
    @comments ntext
    AS

    if exists (
    select *
    from vendor v
    where v.name = @name
    )
    BEGIN
    Raiserror(‘%s already exists!’,16,2,@name)
    END

    if @@error=0
    BEGIN
    INSERT INTO vendor (Name,CountOfPayments,LastPayDate,NextPayDate,Comments)
    VALUES (@Name,@CountOfPayments,@LastPayDate,@NextPayDate,@Comments)
    SELECT @@Identity
    END

    RETURN

    GO

  5. I forgot to thank “Om Mohokar” for his post, cheers mate.

  6. Hi Tom,

    This is the best article I have ever found online. Your instruction is extremely easy and helpfulfor me to understand and use for my work.
    Truly appreciate you!
    Best regards,
    Patrick

  7. Unfortunately, far more complex stored procedures have been written, Bryan, but I will walk through it quickly.

    The first two lines are an example of how to declare variables in your stored procedure. DECLARE…uh, declares the variable. SET assigns the variable with a value. You can also do something like SELECT 1 INTO FROM .

    The block that the first lines belong too just serve as an example. Other than the variables it is much like this article explained. Obviously, in the third line, the parameter declaration has values assigned to them.

    The second block is searching for an existing version of a stored procedure with the name ‘sproc_insertvendor’. If it exists, then drop it so that you can create your new one or your new version if you are running this more than once.

    Nothing really new in the third block although I would like to add a side note. To make a parameter optional, you can add a default value (e.g. @countOfPayments INT = 0) which is extremely valuable information to me at least.

    The fourth block introduces you to Raiserror. I don’t personally know if this is built into SQL Server or not, but it is setting the @@error variable. @@ delineates system or global variables the best I can tell.

    Finally, the fifth block is inserting a row as long as the person doesn’t already exist.

    One last side note: try not to write if exists(select *… If you just wanna know if it exists, if exists(select 1… is more performant and gives you the same information you wanted to know.

    Good article, author. I need to find one for advanced beginners now.

  8. Thanks but one important part not mentioned here is “how to modify the stored procedure and save it as the same stored procedure?”

    Right click on the edited query editor page and execute it to save the changes to the stored procedure.(when you change and try to close it prompts you to change as a query, but not as the stored procedure.

  9. Best explanation about stored I have come accross until now.
    @toughdeep:
    here is a syntax to modify a store procedure:

    Alter procedure usp_procedurename
    as
    select*from table
    go.

Software Reviews | Book Reviews | FAQs | Tips | Articles | Performance Tuning | Audit | BI | Clustering | Developer | Reporting | DBA | ASP.NET Ado | Views tips | | Developer FAQs | Replication Tips | OS Tips | Misc Tips | Index Tuning Tips | Hints Tips | High Availability Tips | Hardware Tips | ETL Tips | Components Tips | Configuration Tips | App Dev Tips | OLAP Tips | Admin Tips | Software Reviews | Error | Clustering FAQs | Performance Tuning FAQs | DBA FAQs |