Presentation is loading. Please wait.

Presentation is loading. Please wait.

College of Business A Quick Introduction to Stored Procedure and Trigger Syntax To Proc or not to Proc Multi-Platform Implications DB Utilities and Reliance.

Similar presentations


Presentation on theme: "College of Business A Quick Introduction to Stored Procedure and Trigger Syntax To Proc or not to Proc Multi-Platform Implications DB Utilities and Reliance."— Presentation transcript:

1 College of Business A Quick Introduction to Stored Procedure and Trigger Syntax To Proc or not to Proc Multi-Platform Implications DB Utilities and Reliance on System Data Module Independence (Coupling and Cohesion) Development Team -Skills -Size -Risks Technical Details Passing Parameters vs. Specifying SQL Syntax Storing Code Modules in the Database Data Independence Returning Values Creating Variables Inserted and Deleted ‘tables’ in Triggers Performance (?)

2 College of Business A Familiar Task Create two tables CREATE TABLE dbo.Weblog( [id] [int] Identity, [host_ip] [nvarchar](16) NULL, [file] [nvarchar](255) NOT NULL, [querystring] [nvarchar](255) NULL, [timestamp] [smalldatetime] NULL ) CREATE TABLE dbo.TechStaffList( [host_ip] [nvarchar](16) NULL ) Does this table structure look familiar? 2

3 College of Business Familiar SQL Syntax Insert a row into the log List the Log Insert a row into the TechStaffList INSERT INTO TechStaffList (host_ip)VALUES ('123.123.123') INSERT INTO Weblog ([host_ip],[file],[querystring],[timestamp]) VALUES ('123.123.123', '/view_lesson.php','url=http://www.te.org/.../lesson07.xml',getdate()) SELECT * from Weblog 3

4 College of Business So What’s the Problem? The syntax requires precise specification of the tables involved (i.e.field names) A couple of issues for conversation: Change the database? Change the program All users have to have insert rights INSERT INTO Weblog ([host_ip],[file],[querystring],[timestamp]) VALUES ('123.123.123', '/view_lesson.php','url=http://www.te.org/.../lesson07.xml',getdate()) 4

5 College of Business Stored Procedures: ‘Methods’ that run in the Database Might it be nice if we could use a function and parameter paradigm instead? We call such things Stored Procedures Name the function, provide params (input) Like a method in a program, a stored procedure can also return things AddWeblogEntry @Source_IP_Address='123.123.123',@TE_File_Requested = '/view_lesson.php',@Querystring = 'url=http://www.te.org/.../lesson07.xml' 5

6 College of Business Creating a Stored Procedure CREATE PROCEDURE AddWeblogEntry @Source_IP_Address nvarchar(16),@TE_File_Requested nvarchar(255),@Querystring nvarchar(255) AS BEGIN INSERT INTO Weblog ([host_ip],[file],[querystring],[timestamp]) VALUES (@Source_IP_Address, @TE_File_Requested, @querystring,getdate() ) END Name the procedure List acceptable parameters Specify the SQL commands to be executed The SQL manager helps a lot, right-click & ‘new stored procedure’ 6

7 College of Business You Can Do More What if you wanted to separate log entries from the technical staff into their own table? Can we let the database (in a stored procedure) handle that instead of writing more code in our C# program? First: Make a new table for tech staff entries CREATE TABLE dbo.TechWeblog( [id] [int] Identity, [host_ip] [nvarchar](16) NULL, [file] [nvarchar](255) NOT NULL, [querystring] [nvarchar](255) NULL, [timestamp] [smalldatetime] NULL ) 7

8 College of Business Now Create a ‘Smarter’ Proc 8 ALTER PROCEDURE AddWeblogEntry @Source_IP_Address nvarchar(16),@TE_File_Requested nvarchar(255),@Querystring nvarchar(255) AS BEGIN declare @IsTechStaff int -- declares a variable for use in this procedure -- In effect this asks if this address is in the list: 0 = no, >0 = yes select @IsTechStaff = count(*) from TechStaffList where host_ip =@Source_IP_Address if @IsTechStaff > 0 Begin INSERT INTO TechWeblog ([host_ip],[file],[querystring],[timestamp]) VALUES (@Source_IP_Address, @TE_File_Requested, @querystring,getdate() ) end else Begin INSERT INTO Weblog ([host_ip],[file],[querystring],[timestamp]) VALUES (@Source_IP_Address, @TE_File_Requested, @querystring,getdate() ) End END

9 College of Business What Result Do You Expect Here? 9 truncate table Weblog -- this clears everything so we can start clean truncate table TechWeblog -- Note this is exactly the syntax as before, programs that CALLS the proc need NOT change exec AddWeblogEntry '123.123.121', '/view_lesson.php', 'url=http://www.te.org/.../l1.xml' exec AddWeblogEntry '123.123.122', '/view_lesson.php', 'url=http://www.te.org/.../l2.xml' exec AddWeblogEntry '123.123.123', '/view_lesson.php', 'url=http://www.te.org/.../l3.xml' exec AddWeblogEntry '123.123.124', '/view_lesson.php', 'url=http://www.te.org/.../l4.xml' exec AddWeblogEntry '123.123.121', '/view_lesson.php', 'url=http://www.te.org/.../l5.xml' select * from WebLog select * from TechWeblog

10 College of Business Even Wilder…. Triggers What if we often realize after the fact that certain IP addresses are part of the tech staff? We can have the database to perform special procedures called triggers whenever data in a table is changed (UPDATE, INSERT, or DELETE). So, this is a bit far fetched – given the frequency of changes and other issues. This example may not justify a trigger. But, lets go with it to understand HOW a trigger works. 10

11 College of Business Create A Trigger 11 CREATE TRIGGER dbo.Tr_TechStaff_IPAddress_Change ON dbo.TechStaffList FOR INSERT,UPDATE,DELETE AS BEGIN SET NOCOUNT ON; -- avoids extra result sets that would be generated -- When records are Deleted or Updated, the old contents are listed in 'deleted' -- So, we will move any log records for this ip from the Tech list back to the main list INSERT INTO Weblog ([host_ip],[file],[querystring],[timestamp]) SELECT TechWebLog.[host_ip],[file],[querystring],[timestamp] from TechWebLog, deleted where TechWebLog.host_ip = deleted.host_ip Delete TechWebLog where host_ip in (select host_ip from deleted) -- When records are inserted or updated, the new contents are listed in the table 'inserted' -- So our code will 'move' all the records in WebLog to TechWebLog for these addresses INSERT INTO TechWeblog ([host_ip],[file],[querystring],[timestamp]) SELECT WebLog.[host_ip],[file],[querystring],[timestamp] from WebLog, inserted where WebLog.host_ip = inserted.host_ip Delete WebLog where host_ip in (select host_ip from inserted) END

12 College of Business What Result Do You Expect Here? 12 truncate table Weblog ; truncate table TechWeblog; truncate table TechStaffList -- clear old stuff exec AddWeblogEntry '123.123.121', '/view_lesson.php', 'url=http://www.te.org/.../l1.xml' exec AddWeblogEntry '123.123.122', '/view_lesson.php', 'url=http://www.te.org/.../l2.xml' exec AddWeblogEntry '123.123.123', '/view_lesson.php', 'url=http://www.te.org/.../l3.xml' exec AddWeblogEntry '123.123.124', '/view_lesson.php', 'url=http://www.te.org/.../l4.xml' exec AddWeblogEntry '123.123.121', '/view_lesson.php', 'url=http://www.te.org/.../l5.xml' select * from WebLog; select * from TechWebLog; select * from TechStaffList INSERT INTO TechStaffList (host_ip)VALUES ('123.123.123') select * from WebLog; select * from TechWebLog; select * from TechStaffList INSERT INTO TechStaffList (host_ip)VALUES ('123.123.121') select * from WebLog; select * from TechWebLog; select * from TechStaffList DELETE TechStaffList where host_ip = '123.123.121' select * from WebLog; select * from TechWebLog; select * from TechStaffList

13 College of Business So – That Was a Quick Intro Now lets look at the notes on line 13

14 College of Business Production Interfaces Accounts Receivable Application Extending Credit to Customers Application Architecture Database EDI supports efficient customer processes Sales identifies new customers Credit managers adjust credit limits Web store allows direct sales Direct DB access through utility apps Business Logic Policies and access controls reduce risk Processing instructions enact transactions

15 College of Business Risk Number 1: Bad Credit limits The Business Risk: If credit limits are changed inappropriately, we might ship product for which we will never be paid Control: Only selected individuals are authorized to set or change credit limits Control implementation – programs that change limits must check a list of authorized people before changing a limit – changes are logged for verification 15

16 College of Business More Risks: Errors or Hacks in a Heterogeneous Environment Risk: Given the multiple interfaces that might change the limits, some one of many components may have an error that could result in wrong credit limit data Risk: Someone could go in with a utility program or an SQL injection attack and change a limit thereby avoiding coded controls – This might be inadvertent or fraudulent Can you see how stored procedures or triggers could help here? 16

17 College of Business What needs to be done to change a customer’s credit limit? Who am I? May I? Do it Log it Display A database lists users in roles This role is called ChgClientCreditLimit if ( (Select count(*) where Person, Role) > 0) OK Get the user name from the system Windows handles this when it connects to the DB Worked? Remember what was done by whom Forbidden? Remember who tried Update Clients Set CreditLimit=?, this customer Tell the user what happened 17

18 College of Business Scenario 1 – Client Heavy C#.Net Connect, Authenticate, Check for success Specify authorization parameters Specify tables, columns, and SQL Execute and check success Specify update parameters Specify tables, columns, and SQL Execute and check success Specify logging parameters Specify tables, columns, and SQL Execute and check success Specify Results parameters Specify tables, columns, and SQL Execute and check success Display results DB Server ‘Blindly’ perform SQL instructions 3 pages of C# code with embedded table/column names, authorization rules, and business logic 18

19 College of Business Scenario 2 – Stored Proc Connect, Authenticate, Check for success Specify authorization parameters Specify tables, columns, and SQL Execute and check success Specify update parameters Specify tables, columns, and SQL Execute and check success Specify logging parameters Specify tables, columns, and SQL Execute and check success Specify Results parameters Specify tables, columns, and SQL Execute and check success Display results DB Server Half the C# code but involved DB procedure code: authorization logic, logging functions, and table/column details are not included in the C# program Stored Procedure ChgClientCreditLimit Exec Stored Proc  19 C#.Net

20 College of Business Scenario 3 – Proc + Trigger Connect, Authenticate, Check for success Specify authorization parameters Specify tables, columns, and SQL Execute and check success Specify update parameters Specify tables, columns, and SQL Execute and check success Specify logging parameters Specify tables, columns, and SQL Execute and check success Specify Results parameters Specify tables, columns, and SQL Display results DB Server Logging is moved into a trigger. Changes are logged no matter how the updates are made: code, proc, or utility In our lab, authorization is also moved to its own proc, AuthCheck,which logs denied attempts Stored Procedure ChgClientCreditLimit Database Trigger Logs the Activity Exec Stored Proc  Trigger Fires Automatically  20 C#.Net

21 College of Business Things to Ponder Which solution has the most cohesive modules? How is data independence affected? Heterogeneity: Web? Automated? Mobile? – What will an interface programmer need to know? Reliability, performance, and control – DB locks, speed, memory, impact of an error, restoring data, cross-platform consistency – Compare the security of a single logging proc and auth proc vs. SQL in multiple code modules Moving functionality from client, to web server, to DB code profoundly affects a variety of important issues. Which is best? IT DEPENDS 21


Download ppt "College of Business A Quick Introduction to Stored Procedure and Trigger Syntax To Proc or not to Proc Multi-Platform Implications DB Utilities and Reliance."

Similar presentations


Ads by Google