Download presentation
Presentation is loading. Please wait.
Published byEllen Clark Modified over 8 years ago
1
Instructor: Craig Duckett Lecture 15: Tuesday, May 17 th, 2016 Again Stored Procedures and Functions 1
2
2 Assignment 3 is due LECTURE 20, Thursday, June 2 nd, in StudentTracker by MIDNIGHT FINAL EXAM is due LECTURE 21, Tuesday, June 7 th We will be looking at Microsoft SQL Server, Azure, virtual server, and Visual Studio until the end of the quarter.
3
3 3 x 150 Points (450 points Total) Assignment 1 (Stage 1): Due Thursday, April 7 th Assignment 2 (Stage 2): Due Tuesday, May 3 rd Assignment 3 (Stage 3): Due Thursday, June 2 nd
4
4 Tuesday/Thursday (LECTURE 14) Database Design for Mere Mortals: Chapters 10, 11
5
5 SQL Sample Databases Stored Procedures (Re-Introduction) TRY -- CATCH SQL Functions PLEASE NOTE: Today’s lecture is mostly a “mile high” overview, and contains a lot of information that will likely be well over-your-head until such a time comes you want to drill down into it for greater understanding. The scope of this class, with its limited time frame, as well as your burgeoning understanding of SQL and DBMSs, do not support such drilling into. The purpose of this class is to “drop some seeds” into your general knowledge of SQL Server, so you might better understand its power and potential. That is all. In short, don’t get anxious if most of this is flying over your heads. https://www.udemy.com/sql-server-for-beginners/https://www.udemy.com/sql-server-for-beginners/ (free) https://www.udemy.com/introduction-to-learn-t-sql-from-scratch/https://www.udemy.com/introduction-to-learn-t-sql-from-scratch/ (free)
6
SQL Server: Sample Databases http://sqlserversamples.codeplex.com/
7
SQL Server: Stored Procedures (Re-Introduction) A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again. So if you think about a query that you write over and over again, instead of having to write that query each time you would save it as a stored procedure and then just call the stored procedure to execute the SQL code that you saved as part of the stored procedure. In addition to running the same SQL code over and over again you also have the ability to pass parameters to the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the parameter values that were passed Storing the code inside the SQL Server object offers many advantages, like: Security due to encryption Performance gains due to compilation Being able to hold the code in a central repository: Altering the code in SQL Server without replicating in several different programs Being able to keep statistics on the code to keep it optimized Reduction in the amount of data passed over a network by keeping the code on the server Hiding the raw data by allowing only stored procedures to gain access to the data
8
SQL Server: Stored Procedures (Re-Introduction) You may have executed some ad-hoc queries for tasks like inserting data, querying information in other systems, or creating new database objects such as tables. All these tasks can be placed within a stored procedure, so that any developer can run the same code without having to recreate the T-SQL commands. Also, generalizing the code for all values makes it generic and reusable. Stored procedures are more than just tools for performing repetitive tasks. There are two main types of stored procedure – system stored procedures and user-defined stored procedures. Extended stored procedures give functionality that is not necessarily contained within SQL Server, like allowing DOS commands to run and working with e-mail. It is also possible to create your own extended stored procedures.
9
SQL Server: Stored Procedures (Re-Introduction) Example of a Stored Procedure: USE toy_auction_v4 GO CREATE PROCEDURE optionalParametersTest @name varchar(50), @phone varchar(20), @address varchar(50) = NULL, -- Optional Paramaters are assigned a default value of null @city varchar (50) = NULL -- Put these optional parameters last AS INSERT INTO Owners(name,phone,address,city) VALUES ( @name, @phone, @address, @city) GO EXEC optionalParametersTest 'Ian Funwinkle', '425-555-5555' -- these are required parameters GO EXEC optionalParametersTest 'Ian Funwinkle', '425-555-5555', '18345 Campus Way' -- with one optional value GO EXEC optionalParametersTest 'Ian Funwinkle', '425-555-5555', '18345 Campus Way', 'Bothell' -- with two optional values
10
SQL Server: Stored Procedures (Re-Introduction) System Stored Procedures In SQL Server, many administrative and informational activities can be performed by using system stored procedures. Every time we add or modify a table, make a backup plan, or perform any other administrative function from within Enterprise Manager, we actually call a stored procedure specifically written to complete the desired action. These stored procedures are known as system stored procedures, which are functions that enhance the basic functionality of SQL Server itself, either by extending the functionality of an existing system stored procedure or by creating new functionality that enhances the basics of what is already there. System stored procedures are prefixed by sp_, so it is not advisable to use sp_ for any of the stored procedures that we create, unless they form a part of our SQL Server installation. Creating a stored procedure prefixed with sp_ and placing it in the master database will make it available to any database without the need to prefix the stored procedure with the name of the database. More details can be found at this link. Let's clarify this with an example. If we take the sp_who stored procedure, call it sp_mywho, store it in the master database, and move to another database, we can still execute sp_mywho, rather than having to specify the procedure in the fully qualified manner as master.dbo.sp_mywho.
11
SQL Server: Stored Procedures (Re-Introduction) User Stored Procedures A user stored procedure is any program that is stored and compiled within SQL Server (but not in the master database) and NOT prefixed with sp_. [I've used either usp_ or usersproc_, or something to that effect] User stored procedures can be categorized into three distinct types: User stored procedures Triggers User defined functions Stored Procedures Best Practices http://sqlblog.com/blogs/aaron_bertrand/archive/2008/10/30/my-stored-procedure-best-practices-checklist.aspx
12
SQL Server: Stored Procedures (Re-Introduction) Creating Stored Procedures Syntax CREATE PROCEDURE ProcedureName AS BEGIN SELECT * FROM TABLE END GO
13
SQL Server: Stored Procedures (Re-Introduction) Creating Stored Procedures Overview As mentioned above a stored procedure is nothing more than stored SQL code that you would like to use over and over again. In this example we will look at creating a simple stored procedure. Explanation Before you create a stored procedure you need to know what your end result is, whether you are selecting data, inserting data, etc.. In the upcoming simple example we will just select all data from the Person.Address table that is stored in the AdventureWorks database (only for the purposes of this slide, since we don’t have the AdventureWorks database installed).
14
SQL Server: Stored Procedures (Re- Introduction) Creating Stored Procedures So the simple T-SQL code would be as follows which will return all rows from this table. SELECT * FROM AdventureWorks.Person.Address To create a stored procedure to do this the code would look like this: CREATE PROCEDURE uspGetAddress AS SELECT * FROM AdventureWorks.Person.Address GO To call the procedure to return the contents from the table specified, the code would be: EXEC uspGetAddress --or just simply uspGetAddress
15
CREATE PROCEDURE FetchAllOrderDetails AS BEGIN SELECT O.OrderID,MONTH(O.OrderDate) Order_Month, P.ProductName,P.UnitPrice,P.UnitsInStock, S.CompanyName FROM Orders O INNER JOIN [Order Details] OD ON O.OrderID=OD.OrderID INNER JOIN Products P ON OD.ProductID=P.ProductID INNER JOIN Suppliers S ON P.SupplierID=S.SupplierID END
17
SQL Server: Stored Procedures (Re-Introduction) Creating Stored Procedures with Parameters Overview The real power of stored procedures is the ability to pass parameters and have the stored procedure handle the differing requests that are made. In this topic we will look at passing parameter values to a stored procedure. Explanation Just like you have the ability to use parameters with your SQL code you can also setup your stored procedures to except one or more parameter values. One Parameter In this example we will query the Person.Address table from the AdventureWorks database, but instead of getting back all records we will limit it to just a particular city. This example assumes there will be an exact match on the City value that is passed. (Again, this is only for the purposes of this slide, since we don’t have the AdventureWorks database installed).
18
Creating Stored Procedures with Parameters One Parameter In this example we will query the Person.Address table from the AdventureWorks database, but instead of getting back all records we will limit it to just a particular city. This example assumes there will be an exact match on the City value that is passed. CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City GO To call this stored procedure we would execute it as follows: EXEC uspGetAddress @City = 'New York' SQL Server: Stored Procedures (Re-Introduction)
19
Creating Stored Procedures with Parameters We can also do the same thing, but allow the users to give us a starting point to search the data. Here we can change the "=" to a LIKE and use the "%" wildcard. CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City LIKE @City + '%' GO In both of the proceeding examples it assumes that a parameter value will always be passed. If you try to execute the procedure without passing a parameter value you will get an error message such as the following: Msg 201, Level 16, State 4, Procedure uspGetAddress, Line 0 Procedure or function 'uspGetAddress' expects parameter '@City', which was not supplied. SQL Server: Stored Procedures (Re-Introduction)
20
Creating Stored Procedures with Parameters Default Parameter Values In most cases it is always a good practice to pass in all parameter values, but sometimes it is not possible. So in this example we use the NULL option to allow you to not pass in a parameter value. If we create and run this stored procedure as is it will not return any data, because it is looking for any City values that equal NULL. CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City GO (CONTINUED NEXT SLIDE) SQL Server: Stored Procedures (Re-Introduction)
21
Creating Stored Procedures with Parameters We could change this stored procedure and use the ISNULL function to get around this. So if a value is passed it will use the value to narrow the result set and if a value is not passed it will return all records. (Note: if the City column has NULL values this will not include these values. You will have to add additional logic for City IS NULL) CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL AS SELECT * FROM AdventureWorks.Person.Address WHERE City = ISNULL(@City,City) GO SQL Server: Stored Procedures (Re-Introduction)
22
CREATE PROCEDURE CustomerProductDetails ( @p_CustomerID NVARCHAR(10) ) AS BEGIN SELECT CAT.CategoryName,CAT.[Description], P.ProductName,P.UnitPrice,P.UnitsInStock FROM Customers C INNER JOIN Orders O ON C.CustomerID=O.CustomerID INNER JOIN [Order Details] OD ON O.OrderID=OD.OrderID INNER JOIN Products P ON OD.ProductID=P.ProductID INNER JOIN Categories CAT ON P.CategoryID=CAT.CategoryID WHERE C.CustomerID=@p_CustomerID END -- EXEC CustomerProductDetails 'ALFKI'
24
SQL Server: Stored Procedures (Re-Introduction) Creating Stored Procedures with Multiple Parameters Setting up multiple parameters is very easy to do. You just need to list each parameter and the data type separated by a comma as shown below CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL AS SELECT * FROM AdventureWorks.Person.Address WHERE City = ISNULL(@City,City) AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1,AddressLine1) + '%' GO To execute this you could do any of the following: EXEC uspGetAddress @City = 'Calgary' -- or EXEC uspGetAddress @City = 'Calgary', @AddressLine1 = 'A' -- or EXEC uspGetAddress @AddressLine1 = 'Acardia' -- etc...
25
CREATE PROCEDURE EmployeeOfTheMonth ( @p_Year INT, @p_Month NVARCHAR(10) ) AS BEGIN SELECT * FROM Employees WHERE EmployeeID IN ( SELECT EmployeeID FROM ( SELECT top 1 EmployeeID, COUNT(OrderID) TotalOrders FROM Orders WHERE YEAR(OrderDate)=@p_Year AND DATENAME(MONTH,OrderDate)=@p_Month GROUP BY EmployeeID ORDER BY TotalOrders DESC ) AS EmployeeOfTheMonth ) END EXEC EmployeeOfTheMonth 1997,'June'
27
SQL Server: Stored Procedures (Re-Introduction) Returning Stored Procedure Parameter Values to a Calling Stored Procedure (OUTPUT) Overview In a previous topic we discussed how to pass parameters into a stored procedure, but another option is to pass parameter values back out from a stored procedure. One option for this may be that you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure. Explanation Setting up output parameters for a stored procedure is basically the same as setting up input parameters, the only difference is that you use the OUTPUT clause after the parameter name to specify that it should return a value. The output clause can be specified by either using the keyword "OUTPUT" or just "OUT".
28
SQL Server: Stored Procedures (Introduction) We will vary the stored procedure we just wrote, this time with an INPUT and OUTPUT parameters. We will try fetching the product details which are supplied by a given supplier ID and will return the supplier’s Contact Name and Company Name. CREATE PROCEDURE FetchSupplierProducts ( @p_SupplierID INT, @p_SupplierName NVARCHAR(30) OUTPUT, @p_CompanyName NVARCHAR(30) OUTPUT ) AS BEGIN SELECT P.ProductID,P.ProductName,P.UnitPrice FROM Products P INNER JOIN Suppliers S ON P.SupplierID=S.SupplierID WHERE S.SupplierID=@p_SupplierID SELECT @p_SupplierName=ContactName,@p_CompanyName=CompanyName FROM Suppliers WHERE SupplierID=@p_SupplierID END
29
SQL Server: Stored Procedures (Introduction) To test the stored procedure, write the following code: DECLARE @v_ContactName NVARCHAR(30) DECLARE @v_CompanyName NVARCHAR(30) EXEC FetchSupplierProducts 1,@v_ContactName OUTPUT,@v_CompanyName OUTPUT SELECT @v_CompanyName CompanyName,@v_ContactName SupplierName
30
TRY – CATCH A First Look The standard error handling construct in many programming languages— including T-SQL—is known as try/catch. The idea behind this construct is to set up two sections (or blocks) of code. The first section, the try block, contains exception-prone code to be “tried.” The second section contains code that should be executed in the event that the code in the try block fails and an exception occurs. This is called the catch block. As soon as any exception occurs within the try block, code execution immediately jumps into the catch block. This is also known as “catching an exception.”
31
SQL Server: Stored Procedures (Introduction) Using TRY CATCH in SQL Server Stored Procedures (TRY…CATCH) Overview A great new option that was added in SQL Server 2005 was the ability to use the Try…Catch paradigm that exists in other development languages. Doing error handling in SQL Server has not always been the easiest thing, so this option definitely makes it much easier to code for and handle errors. Explanation If you are not familiar with the Try...Catch paradigm it is basically two blocks of code with your stored procedures that lets you execute some code, this is the Try section and if there are errors they are handled in the Catch section. Let's take a look at an example of how this can be done. As you can see we are using a basic SELECT statement that is contained within the TRY section, but for some reason if this fails it will run the code in the CATCH section and return the error information.
32
SQL Server: Stored Procedures (Introduction) Using TRY CATCH in SQL Server Stored Procedures As you can see we are using a basic SELECT statement that is contained within the TRY section, but for some reason if this fails it will run the code in the CATCH section and return the error information. In this example we will try to divide 1 by 0 (i.e., SELECT 1/0) CREATE PROCEDURE uspTryCatchTest AS BEGIN TRY SELECT 1/0 END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage; END CATCH http://msdn.microsoft.com/en-us/library/ms175976.aspx
33
SQL Server: Stored Procedures (Introduction) Stored Procedure with Transactions and Try-Catch Block For the next demonstration, we will create three tables and add some faux data in the same. Write the following code to create the three tables and insert some data: CREATE TABLE Dept ( DEPTNO INT PRIMARY KEY, DNAME VARCHAR(20), LOC VARCHAR(20) ) CREATE TABLE Emp ( EMPID INT PRIMARY KEY, ENAME VARCHAR(20), JOB VARCHAR(20), MGRNO INT, SAL DECIMAL(8,2), DEPTNO INT REFERENCES DEPT(DEPTNO) ) CREATE TABLE UpdatedSalTable ( EMPID INT PRIMARY KEY, ENAME VARCHAR(20), JOB VARCHAR(20), MGRNO INT, SAL DECIMAL(8,2), DEPTNO INT REFERENCES DEPT(DEPTNO) )
34
SQL Server: Stored Procedures (Introduction) Stored Procedure with Transactions and Try-Catch Block For the next demonstration, we will create three tables and add some faux data in the same. Write the following code to create the three tables and insert some data: INSERT INTO Dept VALUES(10,'SALES','NORTH') INSERT INTO Dept VALUES(20,'ACCOUNTS','SOUTH') INSERT INTO Dept VALUES(30,'PRODUCTION','WEST') INSERT INTO Dept VALUES(40,'TRAVEL','EAST') INSERT INTO Emp VALUES(1008,'IIII','VP',NULL,1200,10) INSERT INTO Emp VALUES(1000,'AAAA','MANAGER',1008,3200,10) INSERT INTO Emp VALUES(1001,'BBBB','Sales Rept',1000,2200,10) INSERT INTO Emp VALUES(1002,'CCCC','Account Mgr',1008,4200,20) INSERT INTO Emp VALUES(1003,'DDDD','Analyst',1002,5000,20) INSERT INTO Emp VALUES(1004,'EEEE','Analyst',1002,5000,20) INSERT INTO Emp VALUES(1005,'FFFF','Field Manager',1008,7200,30) INSERT INTO Emp VALUES(1006,'GGGG','Prod Eng',1005,3200,30) INSERT INTO Emp VALUES(1007,'HHHH','Site Eng',1005,4200,30)
35
SQL Server: Stored Procedures (Introduction) Stored Procedure with Transactions and Try-Catch Block Now create a stored procedure which will implement the transaction with error handling using TRY-CATCH block. The stored procedure will update the salary of an employee if the location of the employee’s department is ‘SOUTH’ and commit the transaction. It will also store the updated employee’s record into a separate table. SEE NEXT SLIDE
36
CREATE PROCEDURE UpdateEmployeeSalary ( @p_EmployeeID INT ) AS BEGIN DECLARE @v_Location NVARCHAR(10) DECLARE @v_DeptID INT DECLARE @UpdateSal NVARCHAR(20)='Salary Update Transaction' SELECT @v_DeptID = DEPTNO FROM Emp WHERE EMPID=@p_EmployeeID SELECT @v_Location=LOC FROM Dept WHERE DEPTNO=@v_DeptID BEGIN TRY BEGIN TRAN @UpdateSal IF(UPPER(@v_Location)='SOUTH') BEGIN UPDATE Emp SET SAL=SAL+1000 WHERE EMPID=@p_EmployeeID INSERT UpdatedSalTable SELECT * FROM EMP WHERE EMPID=@p_EmployeeID END ELSE BEGIN PRINT 'NO UPDATES' END COMMIT TRAN @UpdateSal END TRY BEGIN CATCH SELECT ERROR_MESSAGE(),ERROR_NUMBER(),ERROR_SEVERITY() ROLLBACK TRAN @UpdateSal END CATCH END
37
Let’s test our stored procedure by writing the following code: EXEC UpdateEmployeeSalary 1002 SELECT * FROM UpdatedSalTable The output of updated employee is as shown below:
38
TRY – CATCH END…For Now
39
SQL Server: Stored Procedures (Introduction) Using Comments with SQL Server Stored Procedures Overview One very helpful thing to do with your stored procedures is to add comments to your code. This helps you to know what was done and why for future reference, but also helps other DBAs or developers that may need to make modifications to the code. Explanation SQL Server offers two types of comments in a stored procedure: line comments and block comments. The following examples show you how to add comments using both techniques. Comments are displayed in green in a SQL Server query window.
40
SQL Server: Stored Procedures (Additional Information) Using Comments with SQL Server Stored Procedures Line Comments To create line comments you just use two dashes " -- " in front of the code you want to comment. You can comment out one or multiple lines with this technique. In this example the entire line is commented out. -- this procedure gets a list of addresses based -- on the city value that is passed CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City GO
41
SQL Server: Stored Procedures (Introduction) Using Comments with SQL Server Stored Procedures Line Comments This next example shows you how to put the comment on the same line. -- this procedure gets a list of addresses based on the city value that is passed CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City -- the @City parameter value will narrow the search criteria GO
42
SQL Server: Stored Procedures (Introduction) Using Comments with SQL Server Stored Procedures Block Comments To create block comments the block is started with "/*" and ends with "*/". Anything within that block will be a comment section. /* -this procedure gets a list of addresses based on the city value that is passed -this procedure is used by the HR system */ CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City GO
43
SQL Server: Stored Procedures (Introduction) Using Comments SQL Server Stored Procedures Combining Line and Block Comments You can also use both types of comments within a stored procedure /* -this procedure gets a list of addresses based on the city value that is passed -this procedure is used by the HR system */ CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City -- the @City parameter value will narrow the search criteria GO
44
SQL Server: Stored Procedures (Introduction) Naming Conventions for SQL Server Stored Procedures Overview One good thing to do for all of your SQL Server objects is to come up with a naming convention to use. There are not any hard and fast rules, so this is really just a guideline on what should be done. Explanation SQL Server uses object names and schema names to find a particular object that it needs to work with. This could be a table, stored procedure, function,etc... It is a good practice to come up with a standard naming convention for you objects including stored procedures.
45
SQL Server: Stored Procedures (Introduction) Naming Conventions for SQL Server Stored Procedures Naming Stored Procedure Action I liked to first give the action that the stored procedure takes and then give it a name representing the object it will affect. So based on the actions that you may take with a stored procedure, you may use: Insert Delete Update Select Get Validate etc... So here are a few examples: uspInsertPerson uspGetPerson spValidatePerson SelectPerson
46
SQL Server: Stored Procedures (Introduction) Naming Conventions for SQL Server Stored Procedures Naming Stored Procedure Object The last part of this is the object that you are working with. Some of these may be real objects like tables, but others may be business processes. Keep the names simple, but meaningful. As your database grows and you add more and more objects you will be glad that you created some standards. So some of these may be: uspInsertPerson - insert a new person record uspGetAccountBalance - get the balance of an account uspGetOrderHistory - return list of orders
47
SQL Server: Stored Procedures (Introduction) Naming Conventions for SQL Server Stored Procedures Schema Names Another thing to consider is the schema that you will use when saving the objects. A schema is a collection of objects, so basically just a container. This is useful if you want to keep all utility like objects together or have some objects that are HR related, etc... This logical grouping will help you differentiate the objects further and allow you to focus on a group of objects. Here are some examples of using a schema: HR.uspGetPerson HR.uspInsertPerson UTIL.uspGet UTIL.uspGetLastBackupDate etc...
48
SQL Server: Stored Procedures (Introduction) Naming Conventions for SQL Server Stored Procedures Do Not Use sp_ as a Prefix One of the things you do not want to use as a standard is "sp_". This is a standard naming convention that is used in the SQL Server master database. If you do not specify the database where the object is, SQL Server will first search the master database to see if the object exists there and then it will search the user database. So avoid using this as a naming convention. Standardize on a Prefix It is a good idea to come up with a standard prefix to use for your stored procedures. As mentioned above do not use "sp_", so here are some other options. usp_ sp usp etc... To be honest it does not really matter what you use. SQL Server will figure out that it is a stored procedure, but it is helpful to differentiate the objects, so it is easier to manage. usp_SomeProcedure spSomeProdedure uspSomeProcedure
49
SQL Server: Stored Procedures (Introduction) Deleting a SQL Server Stored Procedure (DROP PROCEDURE) Overview In addition to creating stored procedures there is also the need to delete stored procedures. This topic shows you how you can delete stored procedures that are no longer needed. Explanation The syntax is very straightforward to drop a stored procedure, here are some examples. Dropping Single Stored Procedure To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC command DROP PROCEDURE uspGetAddress GO -- or DROP PROC uspGetAddress GO -- or DROP PROC dbo.uspGetAddress -- also specify the schema
50
SQL Server: Stored Procedures (Introduction) Deleting a SQL Server Stored Procedure (DROP PROCEDURE) Dropping Multiple Stored Procedures To drop multiple stored procedures with one command you specify each procedure separated by a comma as shown below. DROP PROCEDURE uspGetAddress, uspInsertAddress, uspDeleteAddress GO -- or DROP PROC uspGetAddress, uspInsertAddress, uspDeleteAddress GO
51
SQL Server: Stored Procedures (Introduction) Modifying an Existing SQL Server Stored Procedure (ALTER PROCEDURE) Overview When you first create your stored procedures it may work as planned, but how to do you modify an existing stored procedure? In this topic we look at the ALTER PROCEDURE command and it is used. Explanation Modifying or altering a stored procedure is pretty simple. Once a stored procedure has been created it is stored within one of the system tables in the database that is was created in. When you modify a stored procedure the entry that was originally made in the system table is replaced by this new code. Also, SQL Server will recompile the stored procedure the next time it is run, so your users are using the new logic. The command to modify an existing stored procedure is ALTER PROCEDURE or ALTER PROC
52
SQL Server: Stored Procedures (Introduction) Modifying an Existing SQL Server Stored Procedure Modifying an Existing Stored Procedure Let's say we have the following existing stored procedure that does an exact match on the City. CREATE PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City = @City GO Let's say we want to change this to do a LIKE instead of an equals =. To change the stored procedure and save the updated code you would use the ALTER PROCEDURE command as follows. ALTER PROCEDURE uspGetAddress @City nvarchar(30) AS SELECT * FROM AdventureWorks.Person.Address WHERE City LIKE @City + '%' GO
53
Stored Procedures (Continued) Stored procedures in SQL Server are similar to the procedures you write in other programming languages. Specifically, a stored procedure predefines a batch of code that you store as an object in the database to do work. A stored procedure has the ability to accept parameters, but it does not necessarily need to use parameters. Within a stored procedure, you can use almost all Transact-SQL statements, except another CREATE PROCEDURE statement.
54
Stored Procedures (Continued) SQL Server supports several types of procedures: – System stored procedures that start with an “sp_” (e.g., sp_help) and are stored in the Master and MSDB Databases. – User stored procedures that can be written with either Transact-SQL or Common Language Runtime (CLR) code and are usually stored with a specific database. – Extended stored procedures that historically started with an “xp_” are implemented as dynamic linked libraries (DLLs). http://sqlservernet.blogspot.com/2012/01/related-to-extended-stored-procedure-xp.html http://en.wikipedia.org/wiki/Common_Language_Runtime
55
Stored Procedures (Continued) You should familiarize yourself with at least this list: – sp_add_job [link]link – sp_dboption [link]link – sp_executesql [link]link – sp_help [link]link – sp_helpdb [link]link – sp_configure [link]link – sp_who [link]link – sp_xml_preparedocument [link]link – xp_cmdshell [link]link – xp_sendmail [link]link
56
Stored Procedures (Continued) When deploying applications to a client's server(s) or to a shared SQL Server, there is often a concern that other people might peek at your business logic. Since often the code in a stored procedure can be proprietary, it is understandable that we might want to protect our T-SQL work. There is a trivial way to do this in SQL Server, instead of: You can use the WITH ENCRYPTION option
57
Stored Procedures (Continued) SQL Server stores the text used to create an object, and that anyone may run the sp_HelpText system stored procedure and view it. [link]link If you are a vendor and you wish to guard your intellectual property, consider adding the WITH ENCRYPTION option. This hides the text from copycats. [CONTINUED NEXT PAGE]
58
Stored Procedures (Continued) Now, before you do this, make sure you keep the logic of the stored procedure in a safe place, since you won't have easy access to the procedure's code once you've saved it. Now you will notice that when you try to open the procedure you will receive the following error: http://www.devart.com/dbforge/sql/sqldecryptor/ http://www.3s.placko.eu/ SQL Decryptor 3S SQL Smart Security And when you try to use sp_helptext to view the code You will get the following error
59
Using Procedure Option Statements The WITH RECOMPILE option indicates you don’t want the execution plan cached in memory and that you want it recompiled each time called. The WITH EXECUTE AS clause permits the stored procedure to be run under any designated user’s security context. – Permission must be granted only on the stored procedure itself, without having to grant explicit permissions on underlying or referenced objects. http://www.varindersandhu.in/2011/11/15/sql-server-stored-procedure-with-recompile/ http://dataeducation.com/blog/stored-procedures-and-execute-as
60
Stored Procedure: Input Parameters When creating attributes in a table, you must follow naming convention guidelines, define a data type, and perhaps set a default value. USE AdventureWorks; GO CREATE PROCEDURE uspVendorsByLocation @City VARCHAR(30) = NULL, @State VARCHAR(30) = NULL, @Country VARCHAR(50) = NULL AS BEGIN SELECT V.VendorID, V.Name AS Vendor, A.City, SP.Name AS State, CR.Name AS Country FROM Purchasing.Vendor AS V JOIN Purchasing.VendorAddress AS VA ON VA.VendorID = V.VendorID JOIN Person.Address AS A ON A.AddressID = VA.AddressID JOIN Person.StateProvince AS SP ON SP.StateProvinceID = A.StateProvinceID JOIN Person.CountryRegion AS CR ON CR.CountryRegionCode = SP.CountryRegionCode WHERE (A.City = @City OR @City IS NULL) AND (SP.Name = @State OR @State IS NULL) AND (CR.Name = @Country OR @Country IS NULL) ORDER BY Country, State, City, Vendor END GO
61
TRY – CATCH A Closer Look http://sqlhints.com/2014/01/20/exception-handling-in-sql-server/ http://sqlhints.com/2014/01/25/try-catch-in-sql-server/ http://sqlhints.com/2013/06/30/differences-between-raiserror-and-throw-in-sql-server/ http://sqlhints.com/2014/01/25/exception-handling-template-for-stored-procedure-in-sql-server/
62
Adding Output and Handling Errors Output parameters allow any changes to the parameter that result from the execution of the stored procedure to be retained, even after the stored procedure completes execution. To use an output parameter, you must specify the OUTPUT keyword in both the CREATE PROCEDURE and the EXECUTE statements. If you omit the OUTPUT keyword when you execute the stored procedure, the stored procedure still completes but does not return the modified value. http://msdn.microsoft.com/en-us/library/ms187004%28v=sql.105%29.aspx
63
Adding Output and Handling Errors TRY … CATCH Consider these rules and guidelines when using structured exception handing: – The CATCH block must immediately follow the TRY block. – If a transaction specified in the TRY block (BEGIN TRAN and COMMIT TRAN) generates an error, a jump to the CATCH block occurs, skipping the COMMIT TRAN statement. You probably need to put a ROLLBACK TRAN in the CATCH block to maintain data integrity. TRY … CATCH http://msdn.microsoft.com/en-us/library/ms175976.aspxhttp://msdn.microsoft.com/en-us/library/ms175976.aspx COMMIT TRAN http://msdn.microsoft.com/en-us/library/ms190295.aspxhttp://msdn.microsoft.com/en-us/library/ms190295.aspx ROLLBACK TRAN http://msdn.microsoft.com/en-us/library/ms181299.aspxhttp://msdn.microsoft.com/en-us/library/ms181299.aspx
64
Adding Output and Handling Errors Capture error information with one or more system functions: ERROR_LINE( ) Returns the line number where the error occurred ERROR_MESSAGE( ) Returns the error number of the error that caused the CATCH block of a TRY…CATCH construct to be run. ERROR_NUMBER( ) Returns the error number of the error that caused the CATCH block of a TRY…CATCH construct to be run. ERROR_PROCEDURE( ) Returns the name of the stored procedure or trigger where an error occurred that caused the CATCH block of a TRY…CATCH construct to be run. ERROR_SEVERITY( ) Returns the severity of the error that caused the CATCH block of a TRY…CATCH construct to be run. ERROR_STATE( ) Returns the state number of the error that caused the CATCH block of a TRY…CATCH construct to be run. [link]link [link]link [link]link [link]link [link]link [link]link http://dataeducation.com/blog/sql-server-and-the-try-catch-syntax
65
Changing Stored Procedures You may delete (use the syntax DROP PROC Name) a stored procedure at any time and CREATE a replacement. – This also drops any associated permissions. When changing something about the stored procedure, consider using the ALTER PROC syntax. – This retains the established security context.
66
BEGIN TRY -- This will generate an error, as ProductID is an IDENTITY column -- Ergo, we can't specify a value for this column... INSERT INTO Products(ProductID, ProductName) VALUES(1, 'Test') END TRY BEGIN CATCH SELECT 'There was an error!' + ERROR_MESSAGE() END CATCH TRY – CATCH Example:
67
CREATE PROCEDURE DeleteEmployee ( @EmployeeID int ) AS BEGIN TRY BEGIN TRANSACTION -- Start the transaction -- Delete the Employee's phone numbers DELETE FROM HomePhone WHERE EmployeeID = @EmployeeID -- Delete the Employee record DELETE FROM Employees WHERE EmployeeID = @EmployeeID -- If we reach here, success! COMMIT END TRY BEGIN CATCH -- Whoops, there was an error IF @@TRANCOUNT > 0 ROLLBACK -- Raise an error with the details of the exception DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int SELECT @ErrMsg = ERROR_MESSAGE(), @ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1) END CATCH
68
CLR – Common Language Runtime A Brief Mention
69
Common Language Runtime (CLR) A Common Language Runtime (CLR) procedure sets a reference to a method that supports parameters and becomes cataloged as a procedure in SQL Server. CLR procedures are written in a.NET CLR interpretable language such as Visual Basic.NET or C#. A.NET Framework CLR method exposes a SQL method defined in a.NET assembly.
70
Common Language Runtime (CLR) http://en.wikipedia.org/wiki/Common_Language_Runtime http://en.wikipedia.org/wiki/Common_Intermediate_Language http://en.wikipedia.org/wiki/Bytecode http://en.wikipedia.org/wiki/Native_code
71
Creating CLR Stored Procedures To create a CLR stored procedure, you use a development tool such as Microsoft Visual Studio. The actual syntax in Visual Studio then depends on the language in which you program such as Visual Basic.NET or C#. When you deploy a project to SQL Server, the assembly or DLL file will be cataloged in the SQL database. These objects are displayable by querying the sys.assemblies system view.
72
Enabling the Server for CLR Support Before you can use CLR managed objects, you first need to enable the server for CLR support. sp_configure 'clr_enabled', 1 Reconfigure When a call to a CLR procedure is made without the CLR enabled, an error message that says the.NET Framework is not enabled appears. http://msdn.microsoft.com/en-us/library/ms131048.aspx
73
Enabling the Server for CLR Support The script is pretty simple. Here it is: EXEC sp_configure 'show advanced options', '1'; go reconfigure; go EXEC sp_configure 'clr enabled', '1' go reconfigure; -- Turn advanced options back off EXEC sp_configure 'show advanced options', '0'; go Once you have the CLR enabled, you can write user-defined functions, triggers, stored procedures, user-defined aggregates, and user-defined types in VB.Net and C#. http://msdn.microsoft.com/en-us/library/ms131048.aspx
74
Deployment Guidance Rules and considerations to keep in mind when developing stored procedures: – Temporary stored procedures use the resources of TEMPDB. Minimize their use. – SQL Server saves the connection string parameters specified during stored procedure creation. These settings override any client settings during execution. – Use a naming convention other than “sp_” for your procedures. Consider using “up_” standing for “user procedure.”
75
Deployment Guidance – Create, test, and troubleshoot your stored procedure code on your development workstation. Move it to your production environment during a minimal-use period when you can best afford some glitches. Test it from the client application using normal client permissions. – Design each stored procedure to accomplish a single unit of work. Build a second or a third procedure rather than building one gargantuan hard-to-troubleshoot module. – Qualify object names internal to the stored procedure by their two- part naming convention. This ensures other objects with different schemas remain accessible. TableName.SomeColumnName
76
Processing Stored Procedures When SQL Server processes a stored procedure, the Query Optimizer first checks the procedure cache for an already in-memory execution plan. – If it finds one, it uses that plan to complete the execution request. – Otherwise, it takes the time needed to compile and cache a new execution plan prior to executing the query. Query Optimizer http://msdn.microsoft.com/en-us/library/ff650689.aspxhttp://msdn.microsoft.com/en-us/library/ff650689.aspx
77
Compilation Process The compilation process consists of four stages: 1.Parsing: SQL Server checks for syntax errors and prepares it for optimization. 2.Normalization: SQL Server verifies that all object and column names in the query are correct. 3.Compilation: SQL Server builds the execution plan for the stored procedure, creating query graphs for use by the Query Optimizer. 4.Optimization: A cost-based approach (number of CPU cycles, amount of RAM required, etc.) decides the expense of different possible processing options. The Query Optimizer normally uses the least cost approach. This behavior can be overridden by applying hints.
78
Recompile Hints Sometimes, SQL Server needs to recompile (re-optimize) stored procedure execution plans When you examine the Execution Plan in Query Editor or suspect performance deficiency, you have three options: – The sp_recompile system stored procedure forces a recompile next time run. – Use the WITH RECOMPILE option in the CREATE PROCEDURE statement. – Use the WITH RECOMPILE option with the EXECUTE statement: http://msdn.microsoft.com/en-us/library/ms181647.aspx http://sqltutorials.blogspot.com/2008/03/with-recompile-re-compile-execution.html
79
79 Functions Stored Procedures are pre-compile objects which are compiled for its first time and its compiled format is saved which executes (compiled code) whenever it is called. But a function is compiled and executed every time when it is called. Basic Difference Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values). Functions can have only input parameters for it whereas Procedures can have input/output parameters. Functions can be called from Procedure whereas Procedures cannot be called from Function. Advance Difference Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be. Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function. We can go for Transaction Management in Procedure whereas we can't go in Function. https://blogs.msdn.microsoft.com/pradeepsvs/2014/10/08/difference-between-a-stored-procedure-and-function/
80
Function A function, in any programming environment, lets you encapsulate reusable logic and build software that is "composable", i.e. built of pieces that can be reused and put together in a number of different ways to meet the needs of the users. Functions hide the steps and the complexity from other code. However, in certain respects, SQL Server's functions are fundamentally different from functions in other programming environments. In procedural programming, the piece of functionality that most programmers call a function should really be called a subroutine, which is more like a miniature program. These subroutines can go about changing data, introducing side effects, and generally misbehaving as much as they like. In SQL Server, functions adhere much more closely to their mathematic definition of mapping a set of inputs to a set of outputs. SQL Server's functions accept parameters, perform some sort of action, and return a result. They do all of this with no side effects. Nevertheless, in the same way as subroutines, SQL Server functions can hide complexity from users and turn a complex piece of code into a re-usable commodity. Functions make it possible, for example, to create very complex search conditions that would be difficult and tedious to express in inline T-SQL. https://www.simple-talk.com/sql/t-sql-programming/sql-server-functions-the-basics/
81
Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The function always returns a result or result set from invocation. A function can be called within a SELECT statement or even a WHERE clause, whereas a stored procedure must be called using an EXEC (or EXECUTE) procedure statement.
82
Functions SQL Server supports several types of functions: Built-in functions Scalar functions Inline table-valued functions Multi-statement table-valued functions CLR functions
83
Built-in Functions SQL Server has over 200 built-in functions, but you don't need to become intimately familiar with all of them—just those that you might use as is befitting your particular job or task. large number of functions provided to you by Microsoft. It is a good idea, however, that if you work with SQL Server on a day-to-day basis, are a DBA, or database designer, then you should have a passing familiarity with the different types of functions that are at your disposal. Using BOOKS ONLINE > Functions > Functions [Transact-SQL] is a good place to start http://msdn.microsoft.com/en-us/library/ms174318%28v=sql.105%29.aspx
84
Aggregate Functions Aggregate functions perform operations that combine multiple values into one value by grouping, summarizing, or averaging the values. http://msdn.microsoft.com/en-us/library/ms173454%28v=sql.105%29.aspx AVGMIN CHECKSUM_AGGOVER Clause COUNTROWCOUNT_BIG COUNT_BIGSTDEV GROUPINGSTDEVP GROUPING_IDSUM MAXVAR VARP
85
Row Set Functions Rowset functions return the rowsets that can be used in place of a table referenced in a Transact-SQL statement All rowset functions are nondeterministic. This means these functions do not always return the same results every time they are called, even with the same set of input values.nondeterministic CONTAINSTABLEOPENQUERY FREETEXTTABLEOPENROWSET OPENDATASOURCEOPENXML
86
Ranking Functions [NOTE: I have never had an instance where I needed to use the ranking functions, as these may prove more useful to ranking groups and/or members of various sales forces, etc.] http://www.easkills.com/sqlserver/sqlserverrankingfunctionsrownumberrankdenserankandntile/ Ranking functions allow you to use a rank or a row number within a result set. Ranking functions are nondeterministic functions that return a ranking value for each row in a partition.
87
Built-in Functions Scalar Functions A scalar function returns only a single specific value It can accept multiple parameters, perform various calculations, and then return a single value.
88
Built-in Functions Scalar Functions Configuration FunctionsReturn information about the current configuration. Cryptographic Functions Support encryption, decryption, digital signing, and the validation of digital signatures. Cursor FunctionsReturn information about cursors. Data Type FunctionsReturn information about identity values and other data type values. Date and Time Data Types and Functions Perform operations on a date and time input values and return string, numeric, date and time values. Mathematical Functions Perform calculations based on input values provided as parameters to the functions, and return numeric values. Metadata FunctionsReturn information about the database and database objects. ODBC Scalar Functions Return information about scalar ODBC functions in a Transact-SQL statement. Replication Functions Return information that is used to administer, monitor, and maintain a replication topology Security FunctionsReturn information about users and roles. String Functions Perform operations on a string (char or varchar) input value and return a string or numeric value. System Functions Perform operations and return information about values, objects, and settings in an instance of SQL Server. System Statistical FunctionsReturn statistical information about the system. Text and Image Functions Perform operations on text or image input values or columns, and return information about the value. Trigger FunctionsReturn information about triggers.
89
Built-in Functions Configuration scalar functions return information about system settings. – Configuration functions include server_name( ) and db_name( ), which gives you information about server and database configurations, respectively Cryptographic functions support encryption, decryption, digital signing, and the validation of digital signatures. – EncryptByKey( ) – DecryptByKey( ) Date and time functions provide you with the capability to manipulate and calculate with dates and time values.
90
Mathematical Functions ABSDEGREESRAND ACOSEXPROUND ASINFLOORSIGN ATANLOGSIN ATN2LOG10SQRT CEILINGPISQUARE COSPOWERTAN COTRADIANS All mathematical functions, except for RAND, are deterministic functions. This means they return the same results each time they are called with a specific set of input values. RAND is deterministic only when a seed parameter is specifieddeterministic
91
Security Functions Security functions return information about users and roles. CURRENT_USER (Transact-SQL)SCHEMA_ID (Transact-SQL) DATABASE_PRINCIPAL_ID (Transact-SQL)SCHEMA_NAME (Transact-SQL) sys.fn_builtin_permissions (Transact-SQL)SESSION_USER (Transact-SQL) sys.fn_my_permissions (Transact-SQL)SUSER_ID (Transact-SQL) HAS_PERMS_BY_NAME (Transact-SQL)SUSER_SID (Transact-SQL) IS_MEMBER (Transact-SQL)SUSER_SNAME (Transact-SQL) IS_SRVROLEMEMBER (Transact-SQL)SYSTEM_USER (Transact-SQL) ORIGINAL_LOGIN (Transact-SQL)SUSER_NAME (Transact-SQL) PERMISSIONS (Transact-SQL)USER_ID (Transact-SQL) PWDCOMPARE (Transact-SQL)USER_NAME (Transact-SQL) PWDENCRYPT (Transact-SQL)
92
String Functions String functions manipulate character text. Once again, examine each function in turn. ASCIINCHARSOUNDEX CHARPATINDEXSPACE CHARINDEXQUOTENAMESTR DIFFERENCEREPLACESTUFF LEFTREPLICATESUBSTRING LENREVERSEUNICODE LOWERRIGHTUPPER LTRIMRTRIM
93
Three Function Types A scalar function passes and/or returns a single value. Scalar functions return a data type such as int, money, varchar, etc. A multistatement table-valued function is similar to a stored procedure except that it returns a table. This type of function is suited to address situations where more logic is required than can be expressed in a single query. Inline table-valued functions are functions that return the output of a single SELECT statement as a table data type. Since this type of function returns a table, the output can be used in joins of queries as if it was a standard table.
94
CLR (Common Language Runtime) Functions In the same way you can write managed code procedures, you now can also write a user-defined function in any.NET programming language. Also, as with the scalar functions or a table-valued Transact-SQL function, a managed code (CLR) function can be scalar or table-valued. Before you can use a managed function, you first need to enable CLR support on the server.
95
Deterministic & Nondeterministic Functions SQL Server marks a function as: – A deterministic function always returns the same result, given a specific input value. EXAMPLE: SUM, AVG, DAY, ISNUMERIC, ISNULL – A nondeterministric function nearly always returns a different value each time invoked. EXAMPLE: GETDATE, RAND, @@ROWCOUNT
96
Deterministic Function You can create an index on a computed column if a function is deterministic. – This means whenever you update the row, the index also updates, and you could gain a lot of query performance when using the function in a query expression. User-defined functions are deterministic when they are: – Schema-bound. – Defined with only deterministic user-defined or built-in functions.
97
Schema Binding Schema binding connects the function to the object that it references. – All attempts to drop the object referenced by a schema-bound function fails. – To create a function with the WITH SCHEMABINDING option, the following must be true: All views and user-defined functions referenced by the function must be schema-bound as well. All objects referenced by the function must be in the same database.
98
User-Defined Functions (UDFs) Name? Parameter? SELECT ? FROM ? WHERE ? ORDER BY ? Etc… Return?
99
User-Defined Functions (UDFs) View > Template Explorer Function
100
User-Defined Functions (UDFs)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.