New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Exploring a real-world INSERT procedure

From: SQL Server: Triggers, Stored Procedures, and Functions

Video: Exploring a real-world INSERT procedure

Now I'd like to demonstrate some more complex stored procedures. These are the types of procedures I commonly see on large databases in the real world. They implement business rules as well as enforce data integrity requirements. In order to execute the examples in this section we'll need a new table. I have a text file of data in your folder of exercise files. Let's import that data now. I'll right-click on myDatabase, go to Tasks, and near the bottom we have Import Data. On this screen I'll click Next.

Exploring a real-world INSERT procedure

Now I'd like to demonstrate some more complex stored procedures. These are the types of procedures I commonly see on large databases in the real world. They implement business rules as well as enforce data integrity requirements. In order to execute the examples in this section we'll need a new table. I have a text file of data in your folder of exercise files. Let's import that data now. I'll right-click on myDatabase, go to Tasks, and near the bottom we have Import Data. On this screen I'll click Next.

The first question it asked me is, what's my data source? My data source will be a Flat File and I'll browse to that file now. It's in the Chapter 6 section of your exercise files. This dialog box defaults to text files. What I want is want is actually a CSV, so there we will pick up students.csv, and now it's just a whole bunch of Next, Next, Next, Next, Finish. And I get a bunch of green check mark saying Success. That seems good.

I'll hit a refresh here and I have a new students table. Let's go ahead and look at some of that data. We have things like a student ID, last name, first name, state, some other contact information including an email address, a graduation year, GPA, and a yes or no on whether or not they would like to receive our email newsletter. Great! Now that we have data to work with the first stored procedure I'll implement is an insert stored procedure. I'm going to make up the following fairly plausible hypothetical rules about inserting.

When inserting, every ID must be unique. It's something that could be handled by the database automatically, if it was automatically assigning IDs, but in this hypothetical I'm going to say different system is assigning IDs and as they come in to my system, I want to double-check and make sure they're unique. Also, things like a GPA must be between 0 and 4 with no more than two decimal places. That's something that a front-end application should handle, but it doesn't hurt for me to double-check it. Let's say hypothetically someone else is writing the front-end application and they are either unwilling or unable to make this check.

Then I'll check it on the way into the database and we're going to return a 1 for success or 0 for failure. So I have a stored procedure stage already in your Exercise folder. It significantly longer than some of the stored procedures we've worked with earlier. So I'll walk you through it. We start off of course with keyword, create keyword procedure, and then we have to accept quiet number of parameters. The number of parameters I am accepting is exactly the same as the number of columns in the table. I need one parameter for each field we're going to insert.

Scrolling down a little right after the BEGIN statement, the first I want to do is check to make sure the ID does not already exist in the database. So that's one of my business rules. We have to have unique IDs. So line 18, 19, 20, 21 will perform a query to see how many times this ID already exists. Line 23 checks to see if that number is greater than 0. If it is, it raises an error and returns 0. That is exactly the desired functionality. Once that happens, the code will move on to line 31, 31, 32, 33.

We will format our GPA as two decimal places. That was one of our business requirements and then line 36, make sure the GPA is within a certain range. If the GPA is greater than 4 or less than 0, I am going to return an error to the user again. If we pass that check we're down to lines 44 where it's time to actually attempt the insert, fairly straightforward, INSERT statement. The very last thing I do is check to see the value of a variable @@ROWCOUNT.

This as a very variable I did not create. SQL Server automatically creates and the updates this variable with how many records were modified by the previous statement. If everything worked properly, I should've modified exactly 1 row. So if that value does =1, I'll return a 1 to the user indicating success of the stored procedure. So we'll go ahead and execute that, command(s) completed successfully. I always like hearing that. So there's my stored procedure, Students_Insert.

Now let's go ahead and execute this. I also have a little code stage for you for that. So I am going to try to insert the values, ID 123456, last name Guidry, firstname Martin, some basic contact information there. Notice that 7.1; I am intentionally trying to insert bad data. I am claiming that my GPA is 7.1. Obviously, very ambitious. If our stored procedure functions properly, it should return an error. So let's go ahead and execute. Look at that! It says GPA is invalid.

That is a good catch. So I'll change that to a more realistic value and we will try to run it again, and now it's says one row affected. That likely means success. I'll go check the database here in just a second, but I am going to run it again and it should say ID already exists. So it successfully did the insert the first time. If I try to run it again, it stops me saying this would be a duplicate ID, which is a bad thing. Just to make sure it actually got in there. Let's go ahead and query the table.

That returns exactly 1 row. That's good news. We'll scroll over. You see my GPA there formatted to two decimal places. That was one of the requirements. So it seems like everything is working great.

Show transcript

This video is part of

Image for SQL Server: Triggers, Stored Procedures, and Functions
 
Expand all | Collapse all
  1. 2m 15s
    1. Welcome
      51s
    2. What you should know
      51s
    3. Using the exercise files
      33s
  2. 11m 1s
    1. Comparing triggers, functions, and procedures
      3m 25s
    2. Why use a stored procedure?
      4m 59s
    3. Why use functions?
      1m 27s
    4. Why use triggers?
      1m 10s
  3. 6m 2s
    1. Configuring your environment
      4m 53s
    2. Downloading and installing a sample database
      1m 9s
  4. 26m 25s
    1. Creating a stored procedure
      2m 46s
    2. Modifying a stored procedure
      2m 34s
    3. Returning data using data sets
      3m 45s
    4. Returning data using cursors
      3m 45s
    5. Using input and output parameters
      5m 24s
    6. Using security and permissions
      5m 24s
    7. Using transactions
      2m 47s
  5. 11m 56s
    1. Creating a user-defined function
      4m 59s
    2. Exploring single-value functions
      4m 18s
    3. Exploring table value functions
      2m 39s
  6. 9m 31s
    1. Using "after" triggers
      3m 47s
    2. Using "instead of" triggers
      2m 9s
    3. Using nested triggers
      1m 38s
    4. Using database-level triggers
      1m 57s
  7. 12m 43s
    1. Exploring a real-world INSERT procedure
      5m 32s
    2. Exploring a real-world UPDATE procedure
      3m 13s
    3. Implementing logging on DELETE
      3m 58s
  8. 19m 38s
    1. Understanding the Common Language Runtime (CLR) and the .NET framework
      1m 52s
    2. Using CLR with SQL Server 2012
      4m 11s
    3. Writing stored procedures with C# .NET
      5m 51s
    4. Writing functions with .NET
      5m 7s
    5. Choosing between T-SQL vs. CLR
      2m 37s
  9. 11m 34s
    1. Creating a basic web form and connecting to a database
      2m 56s
    2. Executing a stored procedure
      2m 4s
    3. Passing parameters
      3m 41s
    4. Getting return values
      2m 53s
  10. 1m 43s
    1. Next steps
      1m 43s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.