SlideShare a Scribd company logo
1 of 40
CIS-282
Database Server
 Operates as a separate “process”
 Need to communicate with the server using a separate
application
 Connection required to transmit request and response
 Management Studio and SQL Server are different
programs
Managing SQL Server
 Management Studio gives access to most
functions/operations
 Query window provides method to write/execute T-
SQL statements
 “T” = transact
 SQL Service Manager provides way to start/stop Server
SQL Server Databases
 Two files are maintained
 Data file (.mdf)
 Transaction Log file (.ldf)
 Files can be spread over multiple machines
 Always need a primary file group
Database Contents
 Tables
 User tables hold data
 System tables hold data about the database
 Stored Procedures, User Defined Functions
 Views
 Indexes
Default Databases
 Master: Logins/User roles; system configuration;
names/locations of databases; SQL Server startup
 Tempdb: Lasts duration of SQL Server session;
temporary holding space
 Model: Sets characteristics of new databases
 MSDB: Holds information about jobs SQL Server
Agent runs
Security
 Windows Authentication: Windows network logins
used
 Mixed-mode: Windows OR SQL Server logins used
 Login: To access server
 User: To access a database
 Network security trumps all….
Roles
 Server – administrative functions
 Task based:
 Backup
 Create database
 Roles are fixed
 Database/Application – groups of users with common
activities
 Read/write all data
 Read/write select data
 Read data only
Normalization
 Process for reducing duplicate and redundant data
 1st Normal Form: eliminate repeating groups
 2nd Normal Form: each column in a table depends on
the primary key
 can’t get information with only part of the key
 3rd Normal Form: A column cannot be dependent on
another column that isn’t the primary key
Relationships
 Types
 One-to-one
 One-to-many
 Many-to-many
 Requires a primary key on the ‘one’ side, foreign key on
the ‘many’ side
 Referential Integrity defines how values work across
tables
Table Definition
 Fields need a name and datatype
 SQL Server datatypes are different from Access and
procedural programming language datatypes
 Fieldnames can include spaces – but poor practice
 Identity – create unique number for each row
Constraints
 Allow Null – value not required to add record
 Check Constraints – test field or row values
 Default value – if no data is entered into a field
 Unique – values must be different for each row
Database Diagrams
 Illustrate database design
 Add, modify tables, indexes, relationships
 Can control view, table details
Indexes
 Help to select and find records
 Serve as a “cross-reference”
 Can be based on one or more fields
Good Index Characteristics
 Low maintenance columns
 Includes columns used frequently in Where or Order
By clauses
 Don’t have to go out to table for data
 Help search for ranges of records
Action Queries
 Insert: insert into tablename(fieldlist) values(valuelist)
 Update: update tablename set
field1=value1, field2=value2
 Delete: delete from tablename [where condition]
Select Statement
 Can use an alias for fields and/or tables
 Select fields
 From table
 Join table On field=field
 Inner – both tables have records with matching values
 Outer – all records from one table and any matches found in
second table
Where
 Conditions to determine records returned
 Multiple conditions require And … Or
 Can use where clause to implement join between
tables
 Sub-queries allow tables to be limited by values in a
second table without using a join
Views
 Pre-defined select statement
 Used like a virtual table
SELECT * FROM v_CurrentEmployees
View Performance
 By default views run just as a query processed from
command line
 Adds second step to execution:
 select from view
 execute view itself
 Can add an index to speed execution
 Specific requirements when creating an index on a view
Declaring & Using Variables
 Use Declare
 Must use Set or Select to assign
 Variables are local to a procedure
System Variables
 @@ identifies system variables
 Value of a system variable can change
 @@Rowcount changes with next select, update, insert or
delete
 @@Error changes with each instruction
 @@Identity changes with next insert
Decision-making
 IF … ELSE
 No end if
 Need to use Begin/End if have more than one
instruction to execute
IF StartDate < EndDate
Begin
…
End
ELSE
Simple Case Statement
 CASE
 Similar to SELECT CASE
 Compares one value to different cases
CASE Category
WHEN ‘pop_comp’ THEN ‘Popular Computing’
WHEN ‘mod_cook’ THEN ‘Modern Cooking’
END
Searched Case
 No test expression
 Each WHEN has a boolean test
CASE
WHEN Points >= 90 THEN ‘A’
WHEN Points < 90 AND Extra > 0
THEN ‘A’
END
Errors
 Errors can occur because of SQL statement
 Invalid syntax, or data type
 Errors can also reflect business rules
 Data doesn’t match requirements
Try/Catch
 Similar to .Net languages
 Need to include BEGIN/END
BEGIN TRY
<code>
END TRY
BEGIN CATCH
<error handling code>
END CATCH
BATCH
 Batch is a logical group of SQL statements
 Run-time error will halt execution only of FURTHER
steps
 Can break up multiple steps using GO
 Not available in all tools
 GO causes editing tool to send statements to that point
for execution
 GO isn’t sent to SQL Server
Stored Procedures
 “Code” written in Structured Query Language
 Different from a Script
 Script is a text file that is run
 Sproc is compiled and stored in the database
Using Stored Procedures
 Use Execute to call
 Procedures generate a return value
 Return value is about success of execution
 Exec spName(parameters) doesn’t capture the return
value
 Exec @Variable = spName(parameters) captures return
value
Parameters
 Can use any SQL data type or User Defined Data Types
 Input: Values sent into the stored procedure
 Required unless there’s a default value
 Output: Values sent to the calling routine
 Output parameter is different than return value!
 Must be specified as output; default is an input
parameter
Writing Stored Procedures
 Make modular
 Use RaisError to send a message
 Message can be a string or refer to a message number
 User-defined messages start at 50001 and are stored on
server – not in database!
User-defined Functions
 Similar to stored procedures, but
 Aren’t executed (no EXEC)
 Can be run “in-line” (as part of another SQL statement)
 Return a value (scalar) or table, don’t have a “return
value” or output parameters
Triggers
 Typically used to enforce rules, log activity, or maintain
data (archive)
 Similar to a stored procedure
 Respond to actions on a table
 Trigger is not called
 Trigger is specific to a table
 Table can have multiple triggers
 One trigger can respond to different actions
Triggers & Constraints
 Constraints give better performance
 Triggers can span tables, databases, servers;
constraints are table specific
 If testing a value inserted in one table depends on an
entry in another table, use a trigger
 If testing a value depends on an entry in the current
row, a relationship, or function result, use a constraint
Types of Triggers
 FOR/AFTER execute after data has been written to
tables
 Constraints have already been satisfied
 INSTEAD OF executes before changes are written
 Trigger must complete requested action if appropriate
Update()
 Can test if a column has changed
 Update(columnname)
If Update(FirstName)
Print ‘FirstName has changed’
Transactions
 Provides method for canceling an operation
 Can restore rows, columns to original state in event of
error or business logic failure
 Use when changes will either be committed or
discarded in entirety
 Begin Tran: Identifies the start
 Commit Tran: Write changes
 Rollback Tran: Cancel changes
ACID
 Atomicity: All of the changes will be accepted or none
of the changes will be accepted
 Consistency: Data is either in its original or changed
state
 Isolation: If multiple transactions occur, data is never
available in an intermediate state
 Durability: Once finished, all changes are complete
and changes can only be done by another
transaction/unit of work
Locking & Concurrency
 Locking prevents other operations from changing that
data
 Concurrency refers to multiple actions running against
database at the same time
 What happens if you want to change data I’m working
with?

More Related Content

What's hot

Internet Environment
Internet  EnvironmentInternet  Environment
Internet Environment
guest8fdbdd
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
rspaike
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
lochaaaa
 

What's hot (20)

Internet Environment
Internet  EnvironmentInternet  Environment
Internet Environment
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
Sql2
Sql2Sql2
Sql2
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
Ch 9 S Q L
Ch 9  S Q LCh 9  S Q L
Ch 9 S Q L
 
Versioning
VersioningVersioning
Versioning
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
Intro to t sql – 3rd session
Intro to t sql – 3rd sessionIntro to t sql – 3rd session
Intro to t sql – 3rd session
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Chapter09
Chapter09Chapter09
Chapter09
 
Getting Started with MySQL II
Getting Started with MySQL IIGetting Started with MySQL II
Getting Started with MySQL II
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
Sq lite
Sq liteSq lite
Sq lite
 
The Ultimate Guide to Oracle web logic server 12c administration i 1z0 133
 The Ultimate Guide to Oracle web logic server 12c  administration i  1z0 133 The Ultimate Guide to Oracle web logic server 12c  administration i  1z0 133
The Ultimate Guide to Oracle web logic server 12c administration i 1z0 133
 
Sql database object
Sql database objectSql database object
Sql database object
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
 
[PHPUGPH] PHP Roadshow - MySQL
[PHPUGPH] PHP Roadshow - MySQL[PHPUGPH] PHP Roadshow - MySQL
[PHPUGPH] PHP Roadshow - MySQL
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
WEKA: The Explorer
WEKA: The ExplorerWEKA: The Explorer
WEKA: The Explorer
 

Viewers also liked (7)

Views
ViewsViews
Views
 
NENUG Apr14 Talk - data modeling for netezza
NENUG Apr14 Talk - data modeling for netezzaNENUG Apr14 Talk - data modeling for netezza
NENUG Apr14 Talk - data modeling for netezza
 
Netezza workload management
Netezza workload managementNetezza workload management
Netezza workload management
 
netezza-pdf
netezza-pdfnetezza-pdf
netezza-pdf
 
Using Netezza Query Plan to Improve Performace
Using Netezza Query Plan to Improve PerformaceUsing Netezza Query Plan to Improve Performace
Using Netezza Query Plan to Improve Performace
 
The IBM Netezza datawarehouse appliance
The IBM Netezza datawarehouse applianceThe IBM Netezza datawarehouse appliance
The IBM Netezza datawarehouse appliance
 
Netezza fundamentals for developers
Netezza fundamentals for developersNetezza fundamentals for developers
Netezza fundamentals for developers
 

Similar to CIS 282 Final Review

Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
Syed Asrarali
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 

Similar to CIS 282 Final Review (20)

CIS282 Midterm review
CIS282 Midterm reviewCIS282 Midterm review
CIS282 Midterm review
 
SQL Server Stored procedures
SQL Server Stored proceduresSQL Server Stored procedures
SQL Server Stored procedures
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 
Azure Data Factory Data Flows Training (Sept 2020 Update)
Azure Data Factory Data Flows Training (Sept 2020 Update)Azure Data Factory Data Flows Training (Sept 2020 Update)
Azure Data Factory Data Flows Training (Sept 2020 Update)
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara University
 
Mapping Data Flows Training April 2021
Mapping Data Flows Training April 2021Mapping Data Flows Training April 2021
Mapping Data Flows Training April 2021
 
Adbms
AdbmsAdbms
Adbms
 
Tech Days09 Sqldev
Tech Days09 SqldevTech Days09 Sqldev
Tech Days09 Sqldev
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
SQL Server 2008 for .NET Developers
SQL Server 2008 for .NET DevelopersSQL Server 2008 for .NET Developers
SQL Server 2008 for .NET Developers
 
Module02
Module02Module02
Module02
 
Database testing
Database testingDatabase testing
Database testing
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
Data validation option
Data validation optionData validation option
Data validation option
 
Mapping Data Flows Training deck Q1 CY22
Mapping Data Flows Training deck Q1 CY22Mapping Data Flows Training deck Q1 CY22
Mapping Data Flows Training deck Q1 CY22
 
Db Triggers05ch
Db Triggers05chDb Triggers05ch
Db Triggers05ch
 
Cis266 final review
Cis266 final reviewCis266 final review
Cis266 final review
 

More from Randy Riness @ South Puget Sound Community College

More from Randy Riness @ South Puget Sound Community College (20)

Stored procedures
Stored proceduresStored procedures
Stored procedures
 
3 sql overview
3 sql overview3 sql overview
3 sql overview
 
Normalization
NormalizationNormalization
Normalization
 
CIS160 final review
CIS160 final reviewCIS160 final review
CIS160 final review
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
CIS 245 Final Review
CIS 245 Final ReviewCIS 245 Final Review
CIS 245 Final Review
 
CIS145 Final Review
CIS145 Final ReviewCIS145 Final Review
CIS145 Final Review
 
Cis166 Final Review C#
Cis166 Final Review C#Cis166 Final Review C#
Cis166 Final Review C#
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
CIS245 sql
CIS245 sqlCIS245 sql
CIS245 sql
 
Cis245 Midterm Review
Cis245 Midterm ReviewCis245 Midterm Review
Cis245 Midterm Review
 
CSS
CSSCSS
CSS
 
XPath
XPathXPath
XPath
 
XSLT Overview
XSLT OverviewXSLT Overview
XSLT Overview
 
Schemas 2 - Restricting Values
Schemas 2 - Restricting ValuesSchemas 2 - Restricting Values
Schemas 2 - Restricting Values
 
CIS 145 test 1 review
CIS 145 test 1 reviewCIS 145 test 1 review
CIS 145 test 1 review
 
XML schemas
XML schemasXML schemas
XML schemas
 
Document type definitions part 2
Document type definitions part 2Document type definitions part 2
Document type definitions part 2
 
Document type definitions part 1
Document type definitions part 1Document type definitions part 1
Document type definitions part 1
 
DOM specifics
DOM specificsDOM specifics
DOM specifics
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

CIS 282 Final Review

  • 2. Database Server  Operates as a separate “process”  Need to communicate with the server using a separate application  Connection required to transmit request and response  Management Studio and SQL Server are different programs
  • 3. Managing SQL Server  Management Studio gives access to most functions/operations  Query window provides method to write/execute T- SQL statements  “T” = transact  SQL Service Manager provides way to start/stop Server
  • 4. SQL Server Databases  Two files are maintained  Data file (.mdf)  Transaction Log file (.ldf)  Files can be spread over multiple machines  Always need a primary file group
  • 5. Database Contents  Tables  User tables hold data  System tables hold data about the database  Stored Procedures, User Defined Functions  Views  Indexes
  • 6. Default Databases  Master: Logins/User roles; system configuration; names/locations of databases; SQL Server startup  Tempdb: Lasts duration of SQL Server session; temporary holding space  Model: Sets characteristics of new databases  MSDB: Holds information about jobs SQL Server Agent runs
  • 7. Security  Windows Authentication: Windows network logins used  Mixed-mode: Windows OR SQL Server logins used  Login: To access server  User: To access a database  Network security trumps all….
  • 8. Roles  Server – administrative functions  Task based:  Backup  Create database  Roles are fixed  Database/Application – groups of users with common activities  Read/write all data  Read/write select data  Read data only
  • 9. Normalization  Process for reducing duplicate and redundant data  1st Normal Form: eliminate repeating groups  2nd Normal Form: each column in a table depends on the primary key  can’t get information with only part of the key  3rd Normal Form: A column cannot be dependent on another column that isn’t the primary key
  • 10. Relationships  Types  One-to-one  One-to-many  Many-to-many  Requires a primary key on the ‘one’ side, foreign key on the ‘many’ side  Referential Integrity defines how values work across tables
  • 11. Table Definition  Fields need a name and datatype  SQL Server datatypes are different from Access and procedural programming language datatypes  Fieldnames can include spaces – but poor practice  Identity – create unique number for each row
  • 12. Constraints  Allow Null – value not required to add record  Check Constraints – test field or row values  Default value – if no data is entered into a field  Unique – values must be different for each row
  • 13. Database Diagrams  Illustrate database design  Add, modify tables, indexes, relationships  Can control view, table details
  • 14. Indexes  Help to select and find records  Serve as a “cross-reference”  Can be based on one or more fields
  • 15. Good Index Characteristics  Low maintenance columns  Includes columns used frequently in Where or Order By clauses  Don’t have to go out to table for data  Help search for ranges of records
  • 16. Action Queries  Insert: insert into tablename(fieldlist) values(valuelist)  Update: update tablename set field1=value1, field2=value2  Delete: delete from tablename [where condition]
  • 17. Select Statement  Can use an alias for fields and/or tables  Select fields  From table  Join table On field=field  Inner – both tables have records with matching values  Outer – all records from one table and any matches found in second table
  • 18. Where  Conditions to determine records returned  Multiple conditions require And … Or  Can use where clause to implement join between tables  Sub-queries allow tables to be limited by values in a second table without using a join
  • 19. Views  Pre-defined select statement  Used like a virtual table SELECT * FROM v_CurrentEmployees
  • 20. View Performance  By default views run just as a query processed from command line  Adds second step to execution:  select from view  execute view itself  Can add an index to speed execution  Specific requirements when creating an index on a view
  • 21. Declaring & Using Variables  Use Declare  Must use Set or Select to assign  Variables are local to a procedure
  • 22. System Variables  @@ identifies system variables  Value of a system variable can change  @@Rowcount changes with next select, update, insert or delete  @@Error changes with each instruction  @@Identity changes with next insert
  • 23. Decision-making  IF … ELSE  No end if  Need to use Begin/End if have more than one instruction to execute IF StartDate < EndDate Begin … End ELSE
  • 24. Simple Case Statement  CASE  Similar to SELECT CASE  Compares one value to different cases CASE Category WHEN ‘pop_comp’ THEN ‘Popular Computing’ WHEN ‘mod_cook’ THEN ‘Modern Cooking’ END
  • 25. Searched Case  No test expression  Each WHEN has a boolean test CASE WHEN Points >= 90 THEN ‘A’ WHEN Points < 90 AND Extra > 0 THEN ‘A’ END
  • 26. Errors  Errors can occur because of SQL statement  Invalid syntax, or data type  Errors can also reflect business rules  Data doesn’t match requirements
  • 27. Try/Catch  Similar to .Net languages  Need to include BEGIN/END BEGIN TRY <code> END TRY BEGIN CATCH <error handling code> END CATCH
  • 28. BATCH  Batch is a logical group of SQL statements  Run-time error will halt execution only of FURTHER steps  Can break up multiple steps using GO  Not available in all tools  GO causes editing tool to send statements to that point for execution  GO isn’t sent to SQL Server
  • 29. Stored Procedures  “Code” written in Structured Query Language  Different from a Script  Script is a text file that is run  Sproc is compiled and stored in the database
  • 30. Using Stored Procedures  Use Execute to call  Procedures generate a return value  Return value is about success of execution  Exec spName(parameters) doesn’t capture the return value  Exec @Variable = spName(parameters) captures return value
  • 31. Parameters  Can use any SQL data type or User Defined Data Types  Input: Values sent into the stored procedure  Required unless there’s a default value  Output: Values sent to the calling routine  Output parameter is different than return value!  Must be specified as output; default is an input parameter
  • 32. Writing Stored Procedures  Make modular  Use RaisError to send a message  Message can be a string or refer to a message number  User-defined messages start at 50001 and are stored on server – not in database!
  • 33. User-defined Functions  Similar to stored procedures, but  Aren’t executed (no EXEC)  Can be run “in-line” (as part of another SQL statement)  Return a value (scalar) or table, don’t have a “return value” or output parameters
  • 34. Triggers  Typically used to enforce rules, log activity, or maintain data (archive)  Similar to a stored procedure  Respond to actions on a table  Trigger is not called  Trigger is specific to a table  Table can have multiple triggers  One trigger can respond to different actions
  • 35. Triggers & Constraints  Constraints give better performance  Triggers can span tables, databases, servers; constraints are table specific  If testing a value inserted in one table depends on an entry in another table, use a trigger  If testing a value depends on an entry in the current row, a relationship, or function result, use a constraint
  • 36. Types of Triggers  FOR/AFTER execute after data has been written to tables  Constraints have already been satisfied  INSTEAD OF executes before changes are written  Trigger must complete requested action if appropriate
  • 37. Update()  Can test if a column has changed  Update(columnname) If Update(FirstName) Print ‘FirstName has changed’
  • 38. Transactions  Provides method for canceling an operation  Can restore rows, columns to original state in event of error or business logic failure  Use when changes will either be committed or discarded in entirety  Begin Tran: Identifies the start  Commit Tran: Write changes  Rollback Tran: Cancel changes
  • 39. ACID  Atomicity: All of the changes will be accepted or none of the changes will be accepted  Consistency: Data is either in its original or changed state  Isolation: If multiple transactions occur, data is never available in an intermediate state  Durability: Once finished, all changes are complete and changes can only be done by another transaction/unit of work
  • 40. Locking & Concurrency  Locking prevents other operations from changing that data  Concurrency refers to multiple actions running against database at the same time  What happens if you want to change data I’m working with?