Presentation is loading. Please wait.

Presentation is loading. Please wait.

Simple Programming Part 1 SECTION 7 Procedures and Functions.

Similar presentations


Presentation on theme: "Simple Programming Part 1 SECTION 7 Procedures and Functions."— Presentation transcript:

1 Simple Programming Part 1 SECTION 7 Procedures and Functions

2 Introduction SQL is only a query language T-SQL (SQL) does not have features that allow sophisticated computations

3 Microsoft SQL solution T-SQL Procedures and Functions Looking at basics Users need more sophisticated SQL-oriented programming capabilities

4 Stored Procedures and Functions Lets you use all the SQL data manipulations Fully SQL data types Allows you to do sophisticated processing

5 The Front End Lets you create SQL data manipulations Also lets you do programming The usual front-end displayed to the user

6 Stored Procedures Stored in the database A stored procedure is a group of Transact- SQL statements compiled into a single execution plan.

7 IF (@QuantityOrdered < (SELECT QuantityOnHand FROM Inventory WHERE PartID = @PartOrdered) ) BEGIN -- SQL statements to update tables and process order. END ELSE BEGIN -- SELECT statement to retrieve the IDs of alternate items -- to suggest as replacements to the customer. END A Generic Example

8 Stored Functions A function is designed to return a value used within a larger SQL statemen Functions cannot be used to make changes to the database, whereas stored procedures allow you to do inserts and updates, etc.

9 Triggers EG: When users log on or off Gets executed automatically –Need a triggering event

10 Basic Procedure Structure Four sections –Header section (optional) –Declaration section (optional) –Execution section –Exception section (optional)

11

12 Header Section Anonymous block header The specification of the function -- ================== -- Author -- Create date: -- Description -- ================== Block labels make it easier to read codes

13 Declaration Section (Optional) Ends at keyword –BEGIN Starts with keyword –DECLARE Contains declarations for Variables, constants, cursors, exceptions

14 What are we doing here? When a procedure has finished executing –Declarations stop existing DECLARE @num_a NUMERIC = 6, @num_b NUMERIC;

15 Execution Section Ends with END Starts with keyword –BEGIN

16 Exception Section Ends with END CATCH Starts with keyword –BEGIN CATCH

17 In our example: BEGIN try -- Generate a divide-by-zero error. SET @num_b = 0; SET @num_a = @num_a / @num_b; PRINT @num_a; END try BEGIN catch SELECT ERROR_MESSAGE() AS ErrorMessage; END catch The TRY statement lets you test a block of code for errors The CATCH statement lets you handle the error

18 Creating a Simple Procedure Create procedure test_proc as Select * from customer; We will try the following code

19

20

21

22

23 Use CREATE procedure_name AS procedure_body CREATE PROCEDURE test_proc AS DECLARE @alpha nVARCHAR(30) BEGIN SET @alpha = ‘HELLO WORLD’ PRINT @alpha END

24 Notice the different colouring

25

26 Calling Procedures or Functions Without any parameters Execute procedure_name; With formal parameters Execute procedure_name @alpha = 50, @bravo = 20; A procedure or function may not have formal parameters or default values

27 Variables Storing numbers –NUMERIC datatype Storing text –CHAR, VARCHAR, nVARCHAR datatypes Variables: Essentially containers with name tags

28 Unicode Characters Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems. Unicode's success at unifying character sets has led to its widespread and predominant use in the internationalization of computer software. nVARCHAR All modern operating systems and development platforms use Unicode internally.

29 Declaring Variables A valid variable_name –Up to 30 characters –Letters, 0-9, underscore(_), $, and # –Starts with @ –Cannot use a reserved word that is used by the DBMS The syntax @variable_name datatype or @variable_name (datatype) = default_value_expression e.g.@num_b NUMERIC or @num_a NUMERIC = 6 @num_c NUMERIC(4,2)

30 Datetime2 Text – non-Unicode

31 CREATE PROCEDURE increase_prices @old_price NUMERIC, @percent_increase NUMERIC = 5 AS DECLARE @new_price NUMERIC BEGIN SET @new_price = @old_price + @old_price * @percent_increase/100 PRINT 'New Price: $' + CAST(@new_price as nVARCHAR) END A Simple Procedure – calculates a percent price increase

32 CREATE PROCEDURE increase_prices @old_price NUMERIC, @percent_increase NUMERIC = 5 AS DECLARE @new_price NUMERIC BEGIN SET @new_price = @old_price + @old_price * @percent_increase/100 PRINT 'New Price: $' + CAST(@new_price as nVARCHAR) END

33 CAST The PRINT will print a numeric by itself if there are no other items to be printed. If there are two or more data types that are numeric you must use CAST or CONVERT. @new_price is numeric. Therefore CAST converts @new_price to a nvarchar datatype.

34 CONVERT Works like CAST but structured differently

35

36 Control Structures One can do conditional processing Also can do iterations Many times you may want to do one thing if something is true or something else if it is not true

37 IF Statement The syntax: IF condition_1 BEGIN (SET) Actions_1 END ELSE IF condition_2 BEGIN (SET) Acti ons_2 END …….. ELSE BEGIN (SET) Actions_last END

38 Zodiac Sign YEAR OF BIRTH Rat2008199619841972196019481936192419121900 Bull2009199719851973196119491937192519131901 Tiger2010199819861974196219501938192619141902 Rabbit2011199919871975196319511939192719151903 Dragon2012200019881976196419521940192819161904 Snake2013200119891977196519531941192919171905 Horse2014200219901978196619541942193019181906 Goat2015200319911979196719551943193119191907 Monkey2016200419921980196819561944193219201908 Rooster2017200519931981196919571945193319211909 Dog2018200619941982197019581946193419221910 Pig2019200719941983197119591947193519231911 Want to develop a procedure to calculate your Chinese birth sign.

39 Create procedure CZP @birthyear numeric AS IF @birthyear IN(1900,1912,1924,1936,1948,1960,1972,1984,1996,2008) BEGIN PRINT 'You are a rat' END ELSE BEGIN PRINT 'You are not a rat' END

40

41 CREATE PROCEDURE Chinese_Zodiac_Proc (@BirthDate NUMERIC) --This procedure deals with birth years and the Chinese Zodiac AS PRINT ('*****'); IF @BirthDate IN( 1924, 1936, 1948, 1960, 1972, 1984, 1996) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Rat.') END ELSE IF @BirthDate IN( 1925, 1937, 1949, 1961, 1973, 1985, 1997) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Bull.') END ELSE IF @BirthDate IN( 1926, 1938, 1950, 1962, 1974, 1986, 1998) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Tiger.') END ELSE IF @BirthDate IN( 1927, 1939, 1951, 1963, 1975, 1987, 1999) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Rabbit.') END ELSE IF @BirthDate IN( 1928, 1940, 1952, 1964, 1976, 1988, 2000) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Dragon.') END ELSE IF @BirthDate IN( 1929, 1941, 1953, 1965, 1977, 1989, 2001) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Snake.') END ELSE IF @BirthDate IN( 1930, 1942, 1954, 1966, 1978, 1990, 2002) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Horse.') END ELSE IF @BirthDate IN( 1931, 1943, 1955, 1967, 1979, 1991, 2003) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Sheep.') END ELSE IF @BirthDate IN( 1932, 1944, 1956, 1968, 1980, 1992, 2004) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Monkey.') END ELSE IF @BirthDate IN( 1933, 1945, 1957, 1969, 1981, 1993, 2005) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Rooster.') END ELSE IF @BirthDate IN( 1934, 1946, 1958, 1970, 1982, 1994, 2006) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Dog.') END ELSE IF @BirthDate IN( 1935, 1947, 1959, 1971, 1983, 1995, 2007) BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @BirthDate) + ', the year of the Pig.') END ELSE BEGIN PRINT (' Your birth date is out of the program range!') END PRINT ('*****')

42

43 Now to develop the procedure using a calculation for birth sign 1944/12=162.00MONKEY 1945/12=162.083333ROOSTER 1946/12=162.166667DOG 1947/12=162.25PIG 1948/12=162.33333RAT 1949/12=162.416667BULL 1950/12=162.5TIGER 1951.12=162.583333RABBIT 1952/12=162.666667DRAGON 1953/12=162.75SNAKE 1954/12=162.833333HORSE 1955/12=162.916667SHEEP 1956/12=163.00MONKEY

44 Therefore: SignRemainder (R)R x 12 MONKEY00 ROOSTER0.0833331 DOG0.1666672 PIG0.253 RAT0.333334 BULL0.4166675 TIGER0.56 RABBIT0.5833337 DRAGON0.6666678 SNAKE0.759 HORSE0.83333310 SHEEP0.91666711

45 Thus have to calculate the remainder for each birth year Use @birthyear = 1950 Declare three variables: @X NUMERIC(10,6) @Y NUMERIC(4) @Z NUMERIC(3,2) Now SET @X =@birthyear/12(162.5) SET @Y = @birthyear/12(162) SET @Z = @X - @Y(0.50)

46

47 Multiply by 12. Gets rid of decimal points Only need two significant digits

48 CREATE PROCEDURE Chinese_Zodiac_Proc02 (@birthyear NUMERIC) --This procedure deals with birth years and the Chinese Zodiac AS DECLARE @X NUMERIC(10,6), @Y NUMERIC(4), @Z NUMERIC(2) SET @X = @birthyear/12 SET @Y = @birthyear/12 BEGIN IF @Y > @X SET @Y = @Y-1 SET @Z = (@X - @Y)*12 END PRINT ('*****'); IF @Z = 0 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Monkey.') END ELSE IF @Z = 1 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Rooster.') END ELSE IF @Z = 2 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Dog.') END ELSE IF @Z = 3 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Pig.') END ELSE IF @Z = 4 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Rat.') END ELSE IF @Z = 5 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Bull.') END ELSE IF @Z = 6 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Tiger.') END ELSE IF @Z = 7 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Rabbit.') END ELSE IF @Z = 8 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Dragon.') END ELSE IF @Z = 9 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Snake.') END ELSE IF @Z = 10 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Horse.') END ELSE IF @Z = 11 BEGIN PRINT ('You were born in ' + CONVERT(nVARCHAR(20), @birthyear) + ', the year of the Sheep.') END PRINT ('*****')

49 No correction if @Y > @X Correction if @Y > @X @Z is negative @Z is positive How can @Y be greater than @X?

50

51

52 There is a problem with BCE year as there is no year zero. If the procedure uses ‘0’, the answer is: **** You were born in 0, the year of the Monkey **** This is incorrect as 1 BCE is the year of the Monkey This is corrected in the next slide

53 Correction for year 0 As there is no year 0 you have to increment any BCE years by 1

54

55 WHILE LOOP An iteration construct The Syntax: Declare @counter int Set @counter = 1 While @counter < 10 Begin print 'The counter is ' + cast(@counter as nvarchar) Set @counter = @counter + 1 End OR: Declare @counter int = 1 While @counter < 10 Begin print 'The counter is ' + cast(@counter as nvarchar) Set @counter = @counter + 1 End

56

57

58 Will use the following table: 1.For another loop example; and 2.For a discussion with CURSORS. CREATE TABLE CHINESE_ZODIAC (Number NUMERIC(2) CONSTRAINT cz_pk PRIMARY KEY, ZodiacSign nVARCHAR(10)) INSERT INTO CHINESE_ZODIAC VALUES (0,'Monkey') INSERT INTO CHINESE_ZODIAC VALUES (1,'Rooster') INSERT INTO CHINESE_ZODIAC VALUES (2,'Dog') INSERT INTO CHINESE_ZODIAC VALUES (3,'Pig') INSERT INTO CHINESE_ZODIAC VALUES (4,'Rat') INSERT INTO CHINESE_ZODIAC VALUES (5,'Bull') INSERT INTO CHINESE_ZODIAC VALUES (6,'Tiger') INSERT INTO CHINESE_ZODIAC VALUES (7,'Rabbit') INSERT INTO CHINESE_ZODIAC VALUES (8,'Dragon') INSERT INTO CHINESE_ZODIAC VALUES (9,'Snake') INSERT INTO CHINESE_ZODIAC VALUES (10,'Horse') INSERT INTO CHINESE_ZODIAC VALUES (11,'Goat')

59

60 Declare @counter int Set @counter = 0 While @counter < 7 Begin Select * from Chinese_Zodiac where rounding = @counter Set @counter = @counter + 1 End Simple example of using a While Loop

61

62

63 GOTO LOOP Once again an iteration construct The Syntax: DECLARE @counter INTEGER = 0 EPSILON: BEGIN PRINT 'Hello World' SET @counter = @counter + 1 END IF @Counter < 11 GOTO EPSILON

64

65 According to Microsoft: Use GOTO statement sparingly. Excessive use of the GOTO statement adds difficult to understand the logic of the T-SQL batch. You can almost always implement the logic using other control-of-flow statements. According to Wikipedia: Spaghetti code is a derogatory term for source code that has a complex and tangled control structure, especially one using many GOTO statements, exceptions, threads, or other unstructured branching constructs. It is named such because program flow is conceptually like a bowl of spaghetti, i.e. twisted and tangled. Spaghetti code can be caused by several factors, such as continuous modifications by several people over a long life cycle. Structured programming greatly decreases the incidence of spaghetti code. Problems with GOTO

66 Spaghetti Code

67 An example. Create a function that: Compute discounts on orders Input order amounts Returns discount amount (zero for wrong inputs) The RETURN keyword FUNCTIONS

68 *

69

70 See Part 2 Now


Download ppt "Simple Programming Part 1 SECTION 7 Procedures and Functions."

Similar presentations


Ads by Google