270 likes | 293 Views
Stored Procedures. Dr. Ralph D. Westfall May, 2011. 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
E N D
Stored Procedures Dr. Ralph D. Westfall May, 2011
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/command in a database
Stored Procedures • code to manipulate database • work with data (data manipulation) • manage tables (data definition) • precompiled to run faster • better security • can give users access to data from stored procedures rather than to whole tables
Similarities with Subroutines • can be reused to avoid recoding, make code simpler, avoid redundancy, reduce resource requirements • easier to update than multiple copies • can be used in more than one program • easier to migrate applications to other platforms or scale up to larger volumes
Stored Procedures with SQL Server Management Studio • Click New Query button to create • SSMS doesn’t always seem to work if don’t qualify table and field names • Putting square brackets around field and table names may also help • Right-click a table name>Select Top 1000 Rows to see syntax punctuation • Or refresh Intellisense: [Ctrl]+[Shift]+[R]
Start a New Query • open SQL Server Management Studio and attach the table in OlyNations_Data.zip (OlyNations) • select it and click New Query in toolbar • type SELECT and drag/drop Columns icon from dbo.nations2 and dbo.currencies Tables after SELECT (add comma between groups, and then delete duplicate CID)
Database Names • in a new line, type the word FROM • drag icons for tables (dbo.nations2 and dbo.currencies) and drop them after the from in the query (separate them with a comma) • copy these database table names and paste them before any fields that have the same names in both tables ("Ambiguous column names"), using a dot as a connector • start a new line after table names (Enter)
Where Clause • type the word WHERE in the new line • paste table names from previous line after FROM • replace the comma with = • put a dot (.) after each table name and paste field name (CID) after each table name • click the Execute button in Toolbar • fix errors if necessary • save query with appropriate name for future use
Stored Procedure from Query • Under name of database, expand Programmability • right-click Stored Procedures • right-click Stored Procedures>New Stored Procedure • in CREATE PROCEDURE line, change <Procedure Name etc. > to what you want to call it
Parameters • add parameters with the form of: • @[name] as [datatype] = null [or default], [next parameter] e.g., @country as char(25) = null [or 'Chile'], @golds as int = null, [comma separated] @pop as decimal(7,2) = null [or 3.2] • get datatypes from Columns definitions • default values can help with testing
Add Query • replace SELECT < etc. > with the query you created earlier • add a parameter based selection after the where clause (or make it be the where clause) e.g., and Country = @country
Compile • click Execute button • fix errors if necessary • close query builder window and save file with a filename that identifies it as creating this stored procedure • refresh Object Explorer and verify that stored procedure was created • Rename it to start with usp_
Testing a Stored Procedure • Put database name, stored procedure name, parameter argument(s) into a new query as follows: USE OlyNations; GO EXECUTE dbo.uspGetAll @pop = 100.0 ; GO
Modifying Stored Procedures • right click the stored procedure name in SQL Server Management Studio>Modify • change code as necessary and then click Execute button to store it in the database • close the code window and save the code with a filename that identifies it as modifying this stored procedure
Using Stored Procedures in VB • create or use a VB project that works with a database • in a multi-tier application, most of the changes will be in the data tier • but business rules tier will have to be changed to provide parameters rather than SQL strings
Coding the VB Project • add a ComboBox to select countries, a ListBox for outputs and a Button to trigger selections • download and unzip OlySQLppt.zip • Project>Add Existing Item>select DT2.vb from subdirectory of file you just unzipped
Modify Data Tier Code • AcquireData Function receives a parameter value rather than SQL string • declarations • SQLCommand is stored procedure • SqlParameter is one of the parameters (@[name] in the stored procedure Dim sqlCmd As SqlCommand Dim sqlParm As SqlParameter
More Added Data Tier Code • add the following after the statement that opens the connection [con.Open()] sqlCmd = New SqlCommand() sqlCmd.Connection = con sqlCmd.CommandType = _ CommandType.StoredProcedure sqlCmd.CommandText = "GetNations"
Even More Data Tier Code • rest of added block sqlParmCountry = New _ SqlParameter("@country", selection) sqlParmCountry.Direction = _ ParameterDirection.Input sqlParmCountry.DbType = DbType.String sqlCmd.Parameters.Add(sqlParmCountry)
Test Code • run it and debug as necessary
Multiple Parameter Selection • modify stored procedure to make all parameters default to null • make query ignore missing parameters • change 1st parameter selection: and (@country is null OR Country = @country) • additional parameters in same pattern 'notes
User Interface Modifications • declare each selection and assign selected value or default If ComboBox1.SelectedIndex >= 0 Then contry = ComboBox1.SelectedItem.ToString() Else contry = "none" End If
UI Modifications - 2 • provide error message if no selections are made If [ ]= "none" And [ ] = "none" Then MsgBox("Select [ ] or [ ], or both") Else … [previous line of code to call data tier, modified to handle more arguments
Data Tier Modifications • modify Function to handle additional argument(s) • wrap 1st parameter block in If structure If contryName <> "none" Then • add an If structure for the next parameter • see complete project code
DataGridView UsingStored Procedure • 'notes
Stored Procedure • Pretty lengthy example using stored procedures. How Do I: Understand Data? • Visual Basic programmers will explore how connecting data in a database to controls in Windows Forms applications really works by looking deeper into the DataSet, BindingSource and TableAdapter objects and walking through examples of using data in code.
Or Use Designer for Query • right-click database name>New Stored Procedure then click Query>Design Query in Editor • select tables you want to use>Add>Close • select columns you want>OK