Beruflich Dokumente
Kultur Dokumente
Server
David Henson
dhenson@certifiednetworks.com
www.certifiednetworks.com
Logistics
• Hours: 9:00am to 5:00pm
• Lunch
• Phones
• Parking
Course Material
• Handouts of SQL scripts
• “SQL Server 2008 for Developers”,
Murach press
Recommended Reading
• “Professional SQL Server 2000
Programming”, Wrox Press
• SQLClass Database
– Will be built during class
– \\instructor\public
Tools - Overview
• SQL Management Studio
• Query Editor Window
• SQLCMD.exe
• Books Online
• Misc. Tools:
– Visual Studio .Net 2008
Older Tools:
• Query Analyzer (isqlw.exe)
Microsoft SQL Server Management Studio
Query Editor Window
SQLCMD
•C:\SQLCMD –Sserver -E
• Double Dash
SELECT * FROM Orders -- This is a comment
• Edit/Advanced/Comment Out
Identifiers
• Objects are identified internally by number
• Object Interaction is by name
• Standard Identifiers
– Orders
– Customers
• Delimited Identifiers
– [Spaces are evil]
– [1Person]
Variables
• Must Be Declared
• Must Start with @ symbol
• “Global Variables”
– SELECT @@version
Operators
• +-*/%
• = > < >= <= <>
• Concatination +
• AND, OR, NOT
Expressions
• Symbols and operators that evaluate to a
single value
• Must be used in the context of another
query
Control of flow
• Somewhat limited compared to other
languages
– WHILE
– IF ELSE
– BEGIN END block
– CASE
– WAITFOR
– CONTINUE/BREAK
Lab 2A: T-SQL Language
Elements
• In this instructor led lab, students will
practice using various T-SQL elements
Chapter 3: Foundation T-SQL
Statements
ANSI SQL
• History
• Purpose
• Four Main DML Statements:
– SELECT
– INSERT
– UPDATE
– DELETE
SELECT
• Retrieve/Filter Rows
SELECT <selectlist>
FROM <table1, n…>
WHERE <conditional expression>
ORDER BY <fieldlist>
• Basic Syntax
SELECT *
FROM Orders o
INNER JOIN OrderDetails od
ON o.OrderID = od.OrderID
Join Types
• INNER JOIN
• LEFT OUTER JOIN
• RIGHT OUTER JOIN
• FULL JOIN
• CROSS JOIN
Inner Join
• Exclusive nature of inner join
• Business questions:
1. “Show me all customers, and their
purchases for the month”
2. “Show me all products, and their profit last
week”
Full Join
• All data from both inputs are returned
• Example:
– Employees table contains ManagerID field,
which must be a valid EmployeeID
Chapter 5:Subqueries and
Summary Queries
Grouping Summarizing
• GROUP BY clause is often used for
reporting, in conjunction with joins
• Basic Structure:
SELECT <item>, <aggregate>
FROM <tablelist>
<join sets>
GROUP BY <item>
Having Clause
• Having is the where clause applied to the
aggregated data
UNION all
SELECT
'Grand Total' as 'GrandTotal',
sum(qty * price)
FROM uniondemo
Lab 5A:
Joins/Grouping/Summarizing
• In this lab, students will use joins and
grouping/summarizing to create business
reports
Chapter 6: Creating/Altering
Objects
Object Names
• Four part name must be unique:
– Server.Database.Owner.Object
• Abbreviations
• Sp_addlogin
• Sp_adduser
• GRANT statement
• Scripts
DBCC SHRINKDATABASE
( database_name [ , target_percent ]
[ , { NOTRUNCATE | TRUNCATEONLY } ]
)
DROP Statement
• Destroys object forever
• Examples:
– DROP TABLE Customers
– DROP PROC pr_salesreport
Reverse-Scripting Objects
Information Schema Views
• ANSI SQL method for extracting metadata
– Implemented as a set of views in MS SQL
• Information_schema.tables
• Information_schema.columns
Chapter 6: Constraints
Constraint Types
• Domain
• Entity
• Referential Integrity
Key Constraints
• Primary Key
• Foreign Key
• Unique
Constraint Scope
•Column Level
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY ,
[CustomerEmail] [varchar] (30) NULL ,
[CustomerState] [varchar] (5) NULL
) ON [PRIMARY]
GO
•Table Level
ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID],
[ProductName]
) ON [PRIMARY]
GO
Check Constraints
ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [CK_Products_No_Nissan] CHECK
([Productname] <> 'nissan sentra')
Default Constraints
Disabling Constraints
• Bad Data During Constraint Creation?
ALTER TABLE [dbo].[Products]
WITH NOCHECK
ADD CONSTRAINT [CK_Products_No_Nissan]
CHECK ([Productname] <> 'nissan sentra')
• Default Object
• Non-ansi, outdated
Other Data Integrity Methods
• Triggers
– Good for non-normalized data
• Procedural
– No inserts allowed, only use of Stored Procs that
perform the insert/update/delete after checking data
– Can perform modifications in more than one table
• Application Role
– Client application gets hard coded password
– Updates only allowed through that application
Chapter 7
: Scripts and Batches
Scripts
• Text file containing one or more batches
• Can make use of local variables or system
functions like @@identity
Batches
• A group of on or more SQL statements
into one logical unit
• Any syntax errors in the batch makes the
whole batch fail
• Runtime errors will not undo previous
batch statements
• A batch is not equivalent to a transaction
• Marked by the GO keyword, which is not
sent to the server
Batch Use
• Certain create statements require their
own batch
• Use batches to complete one section of
code before another section starts
• Local variables only have scope in the
current batch
Using EXEC
• Allows dynamic execution of an SQL string
• Cannot reference local variables, only the
string variable it is using
– System vars like @@identity still resolve
• Concatenation should be done in a
variable before passing it to EXEC
• Cannot be used in a UDF
Chapter 8: Views
What is a view
• Stored in the database as a query
• Has standard object name
• Works like a table, with limitations
– Updates restricted
• Provides a layer of abstraction
– Renaming fields
– Hiding fields
• Enterprise edition allows indexing
Creating Views
CREATE VIEW TopSellers
AS
SELECT TOP 10 *
FROM PRODUCTS
ORDER BY ItemsSold
Restrictions
• Expressed as one select statement
– Subqueries and joins are OK
• ORDER BY only allowed if TOP is specified
• Max 1024 columns
• Updates
– Allowed if referencing only one table
– “Instead of” triggers make them updatable in other
cases
• Partioned views increase performance
• Derived columns must have column names
Performance
• Views on Views reduce performance
OPEN demo_cursor
CLOSE demo_cursor
DEALLOCATE demo_cursor
GO
Cursor Options
• GLOBAL/LOCAL
• STATIC
• KEYSET
• DYNAMIC
• FAST FORWARD
The Fetch Statement
• NEXT
• PRIOR
• FIRST
• LAST
• ABSOLUTE
• RELATIVE
@@Fetch_Status
• -2 Means row was deleted
• -1 Means past the last row
– Intent Shared(IS)
• Prevents other transactions from gaining (X)
– Shared(S)
– Update(U)
• Read but can’t update until escalated to (X)
• Exclusive Locks
– Shared with Intent Exclusive(SIX)
– Intent Exclusive(IX)
– Exclusive(X)
– Bulk Update(BU)
– Schema Modification(Sch-M)
Basic Transaction Syntax
BEGIN TRAN [tranname]
--Multiple data edits here
If @@Error = 0
COMMIT TRAN
Else
ROLLBACK TRAN
Considerations
• Exactly two outcomes of a
transaction:success or failure
• Enforced by locks
• Critical for data integrity between tables
– Foreign key only enforces data contents in
one direction
• Contention problems are geometric in
nature
Managing locks
• Sp_who2
• Sp_lock
Chapter 14: .Net/CLR
Integration
Definitions
• CLR
– Common Language Runtime
• Manages Security
• Manages Memory and Cleanup of Resources
• Assembly
– Compiled .Net Code
• .dll
• .exe
– Houses Classes with Methods and Properties
CLR Objects in SQL Server
• Stored Procedures
• Functions
• Triggers
• Aggregate Functions(UDA)*
• User-Defined Types*
– Can perform validation
– Provides for Methods and Types
Or
--Reports to EmployeeID 1
INSERT employees(EmployeeID, EmployeeName, ManagerID)
VALUES(2,'Dave',1)
INSERT employees(EmployeeID, EmployeeName, ManagerID)
VALUES(3,'Anne',1)
--Reports to EmployeeID 3
INSERT employees(EmployeeID, EmployeeName, ManagerID)
VALUES(4,'Alex',3)
INSERT employees(EmployeeID, EmployeeName, ManagerID)
VALUES(5,'Sandy',3)
CTE Heirarchical Example
CREATE FUNCTION SubordinateCount(@ManagerID int)
RETURNS int
AS
BEGIN
DECLARE @count int;
WITH Reports(EmployeeID)
AS
(
SELECT EmployeeID FROM Employees
WHERE ManagerID = @ManagerID
AND EmployeeID <> 1
UNION ALL
SELECT e.EmployeeID FROM Employees e
INNER JOIN Reports r
ON r.EmployeeID = e.ManagerID
)
SELECT @count=count(*)
FROM Reports
RETURN @count
END
CTE Heirarchical Example
select
employeename,
Subordinates=dbo.SubordinateCount(employeeid)
from employees
employeename Subordinates
---------------------------------------- ------------
Andrew 4
Dave 0
Anne 2
Alex 0
Sandy 0
.NET Extensions
• Code can be compiled to an assembly,
then referenced in an SQL query
BEGIN CATCH
PRINT ‘Exception Occurred’
END CATCH
RowNumber()
SELECT
Result=row_number()
OVER(order by employeename asc),
EmployeeName,
Subordinates=dbo.reports(employeeid)
FROM employees
DELETE Employees
OUTPUT deleted.EmployeeID
INTO DeletedEmployeeIDs
PIVOT Clause
CREATE TABLE SALES (
[Year] INT,
Quarter CHAR(2),
Amount FLOAT
)
Year Q1 Q2 Q3 Q4
——- ——— ——— -—— ———
2001 100 190 165 90
2002 200 250 230 180
XML DataType