SQLDEV320A Week 9-1
SQLDEV320A Week 9-1
CURSORS
DATA ACCESS
SECURITY
SQL INJECTION
ENCRYPTION
Writing
• What are Cursors
• Examples
Cursors •
•
Discussions
Pros and Cons
What is a cursor?
A cursor is a database object used by
applications to manipulate data in a set on a
row-by-row basis, instead of the typical SQL
commands that operate on all the rows in
the--set at one time.
Cursor Syntax
DECLARE cursor_name
CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR UPDATE [OF column_name [,...n]]]
Steps to use a Cursor:
--Declare the cursor and associate it with a query
DECLARE <cursorname> CURSOR FOR <query>
--Loop until the end of the cursor is reached WHILE @@FETCH_STATUS = 0 BEGIN
<SQL statements>
--Release resources
DEALLOCATE <cursorname>;
• @@FETCH_STATUS
• 0 Successful
• -1 Failed
• -2 Row missing
System • @@CURSOR_ROWS
• -m The number of rows in the
Cursor keyset
• -1 Dynamic cursor
Functions:
• 0 No cursor has been
opened
• n Total number of rows
in the cursor
•3) CURSOR_STATUS
• 'local' | 'global' | 'variable'
Common Cursor Arguments
Argument Purpose
UPDATE [OF column_name] for update columns within the cursor
FORWARD_ONLY Cursor can only be scrolled from first to the last row
OPEN CustList;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (SELECT COUNT(CustomerID) FROM Sales.Customer) > 0
SELECT AccountNumber FROM Sales.Customer
WHERE CustomerID = @customerid;
PRINT @customerid;
CLOSE CustList;
DEALLOCATE CustList; -- Required to DEALLOCATE
GO
What does this code do?
DECLARE @SPID int
OPEN c_idleSessions
FETCH NEXT FROM c_idleSessions INTO @SPID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'killing process: ' + CAST(@spid as NVARCHAR(5)) EXEC('kill ' + @spid)
FETCH NEXT FROM c_idleSessions INTO @spid
END
CLOSE c_idleSessions;
DEALLOCATE c_idleSessions;
GO
Cursor Discussion:
Choosing a users.
Simple rules:
Cursor Type Use default settings when possible.
Dynamic cursors open faster than static or keyset-driven
cursors.
In joins, keyset-driven and static cursors can be faster
than dynamic cursors.
Keyset-driven or static cursors must be used if you want
to do absolute fetches.
Keyset-driven or static cursors increase the usage of
tempdb.
Cursor Pros and Cons
Pros
They are necessary for some dynamic operations that can't be accomplished with set-based
operations.
They are simple to understand, which makes them ideal for quick-and-dirty programming
A tool of choice for beginner SQL developers or developers who are used to procedural
programming
They outperform while loops when you need row-by-row processing.
They are ideal for scrolling a portion of a large resultsset.
By default, they provide a window into your tables or results set, which maximizes concurrency
Confor
s all applications.
They are procedural iterative functions that are not like database set operations
They are resource intensive and generally slower than other application approaches
They may not scale to support processing and better options are available
They may lock table inserts or updates causing excessiveblocking
There are better alternatives for FOREACH operations
SQL Injection
In a web application, it is common to have users enter input on the
web page. The web application will formulate that into a SQL
string and send it to the database server to execute the SQL
string
Web page:
Server Code:
SQL
Injection
User id:
SQL Injection – Encoded data attack
1
5
DON’T: Parameterized Queries
--1 Standard SQL
SELECT ProductID, Name, ListPrice FROM Production.Product WHERE Name like 'Road
%'
GO
10
Data Access Security
• Hijacking queries with SQL Injection
• Writing parameterized queries
• Object access permissions
Securing the environment
Infrastructure Security Threats
Secure Infrastructure
Managing user
permissions
Monitoring activity
levels
Configuration
monitoring
Application input
validation
20
Restricting Access Permissions
Is data revealing Are you storing Are you subject to Are you under
personally confidential or laws and contractual or
identifiable sensitive business regulations that professional
information (PII)? information? require sensitive obligation to
data encryption? protect your data?
Service Master Key (SMK)
• A symmetric key generated the first time the SQL
Server instance is started
• Encrypt a linked server password, credentials, and
24
Symmetric Keys Asymmetric Keys
Certificates
Can be created externally from SQL
Server and can have expiration
dates
26
Data Encryption
Master Key Management
EncryptByPassphrase()
DecryptByPassphrase()
EncryptByCert()
DecryptByCert()
Supported encryption algorithms: (DES, TRIPLE_DES, RC2, PC4, PC4_128, DESX, AES_128, AES_192,
AES 256)
Encrypt data using a Symmetric
key
DROP MASTER KEY
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'password@1234!'
GO
CREATE CERTIFICATE HR037 WITH SUBJECT = 'EmployeeSSN';
GO
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = AES_256 ENCRYPTION BY
CERTIFICATE HR037;
GO
ALTER TABLE HumanResources.Employee ADD EncryptedNationalIDNumber
varbinary(128);
GO
OPEN SYMMETRIC KEY SSN_Key_01 DECRYPTION BY CERTIFICATE HR037;
GO
UPDATE HumanResources.Employee SET EncryptedNationalIDNumber =
EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
-- remove column
--ALTER TABLE HumanResources.Employee DROP COLUMN
EncryptedNationalIDNumber;
--select top 10 * from HumanResources.Employee
Encrypt data using an Asymmetric
Key
Encrypt data using an Asymmetric
Key
--2 Create Asymmetric Key
CREATE ASYMMETRIC KEY SecureAsymmetricKey WITH ALGORITHM = RSA_2048 ENCRYPTION BY PASSWORD =
N'AReallyStrongPassword!&*';
--3 Create table to store encrypted data
CREATE TABLE AsymmetricTempTable (Id INT IDENTITY(1,1) PRIMARY KEY, PlainText NVARCHAR(100), CipherText
VARBINARY(MAX));
--4 Declare and set variable @str to store plaintext
DECLARE @str NVARCHAR(100) = N'The recipe for the secret Coke formula is...';
c. Speed:
Because it decrypts data in the buffer pool,
TDE allows SQL Server to take advantage of
indexes to improve query performance. Cell-
level encryption requires a performance
tradeoff, which can be very hard to overcome.
Top 10 Security
Tips
Security is a feature – it needs to be planned, tested, and maintained.
Application updates are risky – ensure extra testing and support time.
QUIZ 9 CODING
ASSIGNMENT