1 / 26

Stored Procedures

Stored Procedures. Dr. Ralph D. Westfall May, 2009. Getting Database Data. when using a database, there are two places where a detailed request for data can be located inside a program that is separate from the database inside the database itself

bin
Download Presentation

Stored Procedures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Stored Procedures Dr. Ralph D. Westfall May, 2009

  2. Getting Database Data • when using a database, there are two places where a detailed request for data can be located • inside a program that is separate from the database • inside the database itself • a stored procedure is a previously created query or program in a database

  3. SQL Server Stored Procedures • precompiled in SQL Server so they run faster • can be reused to avoid recoding • make code simpler • like subprocedures do • better security • can give users access to data from stored procedures rather than to whole tables

  4. Stored Procedures • code to manipulate database (retrieve data, add, change, delete) stored in database • like subroutine, can use in multiple programs (but not with Access database) • less storage: once instead of multiple copies • easier to update than multiple copies • stored queries run faster inside database • makes it easier to migrate applications to other platforms or scale up to larger volumes

  5. Stored Procedures with VB • create or open a Visual Basic project • Data>Add new Data Source to get an existing SQL Server database and select the tables that you will use • View>Server Explorer • expand the database you want, right-click Stored Procedures>Add New Stored Procedure

  6. Configure Stored Procedure • change name in top line • http://msdn.microsoft.com/en-us/library/aa258259(SQL.80).aspx • http://databases.about.com/od/sqlserver/a/storedprocedure.htm

  7. Create Stored Procedure • right-click Stored Procedures>New Stored Procedure

  8. Stored Procedures with VB • start SQL Server Management Studio Express • attach or create a database file • right-click database name>New Query • paste in a sample query (e.g., from link above) and modify it to match fields in this database) • run it to see results

  9. Creating Stored Procedures • start SQL Server Management Studio • expand a database>expand Programmability>right-click Stored Procedures>New Stored Procedure • click Query in top menu>Specify Values for Template Parameters • replace values for ProcedureName, @Param[], Datatypes and Default Values

  10. Complete Stored Procedure • replace SELECT statement with SQL code for the procedure • parameters usually are in WHERE clause WHERE [field] [compare] @[name] e.g., WHERE AGE= @age • use Query>Parse to verify syntax • click !Execute button to compile it • File>Save (rename it)>Save

  11. Verify Stored Procedure • click Refresh icon in Object Explorer • expand [database name]> Programmability>Stored Procedures to verify that it's there

  12. Test Stored Procedure • click New Query and type the following:USE "database name"; 'within quotes GOEXECUTE [stored proc name] @[name] = [value], @[name2] = [value2];GO • ignore warnings • click !Execute button and verify results

  13. Sample Code • uses Nations.mdf database from Classy Project • stored procedure is named dbo.GetByPopGolds SELECT * from nations2 where Pop > @pop and Gold < @gold

  14. Add Procedure to Code • create a VB Project with a ListBox, two Textboxes and a Button • double click the Button to create a Sub and add code on following pages

  15. Declarations Dim sqc As SqlCommand Dim da As SqlDataAdapter Dim ds As DataSet Dim con As SqlConnection Dim dr As DataRow Dim output As String Dim pads() As Integer = {4, 22, 3, 3, 3, 7, 15} Dim padDirection() As String = {"L", "R", "L", "L", "L", "L", "R"}

  16. Connection Code ds = New DataSet con = New SqlConnection con.ConnectionString ="server=.\SQLEXPRESS;" _ & AttachDbFilename=[path]\Nations.mdf;" _ & "Integrated Security=True;"

  17. Getting Data sqc = New SqlCommand sqc.CommandText = "Exec [dbo].[GetByPopGolds] " _ & TextBox1.Text & ", " & TextBox2.Text sqc.Connection = con da = New SqlDataAdapter da.SelectCommand = sqc da.Fill(ds) ListBox1.Sorted = True

  18. Load Outputs For Each dr In ds.Tables(0).Rows output = "" For i As Integer = 0 To 6 If padDirection(i) = "L" Then output += CStr(dr(i)).PadLeft(pads(i)) & " " Else output += CStr(dr(i)).PadRight(pads(i)) End If Next ListBox1.Items.Add(output) Next

  19. Using Optional Parameters • Optional Parameters in SQL Stored Procedures • create a stored procedure based on the code at the above web page • right click the stored procedure name> Execute Stored Procedure>either check Pass Null Value or input the desired criterion (don't do both!), OK and review output

  20. Dynamic SQL • include SQL code in parameters rather than just values • potential security risks (SQL injection) • potential to create more flexible stored procedures • more options

  21. Microsoft Access • can create stored procedures in VB code • http://www.devcity.net/Articles/18/msaccess_sp.aspx

  22. Creating a Stored Procedure • download sample.mdb into the project folder • create a query using design view • can also use query from form or report • see Help on saving SQL statements as queries • use Save As to save query within the database with the name you give it

  23. Additional Activity • try to modify code to run the Query that you created in the database

More Related