Download presentation
Presentation is loading. Please wait.
1
Programming Microsoft SQL Server
David Henson
2
Logistics Hours: 9:00am to 5:00pm Lunch Phones Parking
3
Course Material Handouts of SQL scripts
“SQL Server 2008 for Developers”, Murach press
4
Recommended Reading “Professional SQL Server 2000 Programming”, Wrox Press One of the best technical resources: “Inside SQL Server 2000”, Microsoft Press
5
Course Outline Chapter 1: Configuration/Tools
Chapter 2: T-SQL Language Elements Chapter 3: Foundation T-SQL Statements Chapter 4: Joins Chapter 5: Subqueries and Summary Queries Chapter 6: Changing Data Chapter 7: Scripts, Batches and TSQL Extensions
6
Course Outline Chapter 8: Views Chapter 9: Stored Procedures
Chapter 10: User Defined Functions Chapter 11: Triggers Chapter 12: Cursors Chapter 13: Transactions and Locks Chapter 14: CLR Integration
7
Chapter 1: Configuration/Tools
8
Machine Setup Windows 2003, Standard Installation
SQL Server 2008, Enterprise Edition Trial at SQLClass Database Will be built during class \\instructor\public
9
Tools - Overview SQL Management Studio Query Editor Window SQLCMD.exe
Books Online Misc. Tools: Visual Studio .Net 2008 Older Tools: Query Analyzer (isqlw.exe)
10
Microsoft SQL Server Management Studio
11
Query Editor Window
12
SQLCMD C:\SQLCMD –Sserver -E Osql /? For help, or see books online
13
Books Online Best help possible for syntax
best help possible for strangeness
14
Miscellaneous Tools Profiler Server Config Tool
Surface Area Configuration Tool 2005 Client Config Tool Visual Studio 2005/ 2008
15
Chapter 2: T-SQL Language Elements
16
Statement Types DDL – Data Definition Language DCL DML
CREATE TABLE Orders(….) DCL GRANT SELECT ON Orders To Public DML SELECT Max(OrderDate) From Orders INSERT Orders VALUES(….) DELETE Orders WHERE OrderID = 10 UPDATE Orders SET OrderAmount = 0 WHERE OrderID = 10
17
T-SQL Elements Comments Identifiers Variables Datatypes
System Functions Operators Expressions Control-of-flow
18
Comments Block Comment Double Dash Edit/Advanced/Comment Out
/*Multi-line comments here*/ Double Dash SELECT * FROM Orders -- This is a comment Edit/Advanced/Comment Out
19
Identifiers Objects are identified internally by number
Object Interaction is by name Standard Identifiers Orders Customers Delimited Identifiers [Spaces are evil] [1Person] Relevant Queries: select object_id('products') select * from sysobjects
20
Variables Must Be Declared Must Start with @ symbol
datetime = getdate() See also: SET
21
Datatypes Numbers Bigint - +/- 2 to the 63rd power 8 bytes
Int - +/- 2,147,483, bytes Smallint - 32,768 to 32, bytes Tinyint 0 to byte Bit 0,1 or null bytes Decimal(precision,scale) Default max precision 38 decimals
22
Datatypes Money, Smallmoney Datetime, Smalldatetime Char, Varchar
Getdate() Char, Varchar Nchar, nvarchar Text Timestamp/rowversion Uniqueidentifier Newid()
23
System Functions Getdate() Cast() Convert() “Global Variables”
SELECT
24
Operators + - * / % = > < >= <= <> Concatination +
= > < >= <= <> Concatination + AND, OR, NOT
25
Expressions Symbols and operators that evaluate to a single value
Must be used in the context of another query
26
Control of flow Somewhat limited compared to other languages WHILE
IF ELSE BEGIN END block CASE WAITFOR CONTINUE/BREAK
27
Lab 2A: T-SQL Language Elements
In this instructor led lab, students will practice using various T-SQL elements
28
Chapter 3: Foundation T-SQL Statements
29
ANSI SQL History Purpose Four Main DML Statements: SELECT INSERT
UPDATE DELETE
30
SELECT Retrieve/Filter Rows Over 30 pages of online help!
SELECT <selectlist> FROM <table1, n…> WHERE <conditional expression> ORDER BY <fieldlist> Over 30 pages of online help!
31
INSERT Adds new rows to tables INSERT Customers VALUES( ‘Henson’,
‘Dave’, )
32
Update Modifies existing records
33
Delete Wipes out rows forever Truncate Table Customers
34
Temp tables Preceed object name with a # during creation
New in SQL 2000 – table variables
35
Lab 3A: Foundation T-SQL
In this instructor led lab, we will establish business requirements and build our class database from the ground up.
36
Chapter 4: Joins
37
Data Environments OLTP OLAP Structured/Optimized for transactions
Data is organized in many tables OLAP Structured/Optimized for reporting Large space requirements Redundant Data
38
Putting Things Back Together Again
Joins pull together data from two or more tables Basic Syntax SELECT * FROM Orders o INNER JOIN OrderDetails od ON o.OrderID = od.OrderID
39
Join Types INNER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN FULL JOIN
CROSS JOIN
40
Inner Join Exclusive nature of inner join
Only rows that match in both input tables are returned
41
Outer Join All rows from “left” or “right are returned
Any matching rows from the other side are returned Business questions: “Show me all customers, and their purchases for the month” “Show me all products, and their profit last week”
42
Full Join All data from both inputs are returned
Null is returned in cells where there is no intersection
43
Cross Join Cartesian product of two inputs Produces all intersections
Can produce mass amounts of data…good for populating databases
44
Joining multiple tables
Every join is between two “input” tables One table could be an “intermediate result” of another join Many errors(and hours of frustration) come from improper mixing of inner and outer joins
45
Self Joins Join a table to itself for recursive lookups
Must use table aliases Example: Employees table contains ManagerID field, which must be a valid EmployeeID
46
Chapter 5:Subqueries and Summary Queries
47
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>
48
Having Clause Having is the where clause applied to the aggregated data SELECT ProductID, Sum(SaleAmount) FROM Sales GROUP BY ProductID HAVING Sum(SaleAmount) > 1000
49
Aggregate functions Count(), Count(*) Sum() Min() Max() Avg()
Ceiling() Floor() Other statistical aggregates…
50
Unions Joins two complete result sets together
Field number and types must match Good for adding summary lines to reports and pulling data together from multiple servers
51
Union Example SELECT Convert(varchar(20),saleDate,101),
qty * price as 'Amount' FROM uniondemo UNION all 'Grand Total' as 'GrandTotal', sum(qty * price)
52
Lab 5A: Joins/Grouping/Summarizing
In this lab, students will use joins and grouping/summarizing to create business reports
53
Chapter 6: Creating/Altering Objects
54
Object Names Four part name must be unique: Short vs. Long
Server.Database.Owner.Object Short vs. Long Abbreviations Using Natural Language Queries
55
Granting Access to Objects
Three layers of SQL Security: Login Windows or Standard User Database specific membership, tied to the login Object Permissions Permissions and permission type specific to the object Sp_addlogin Sp_adduser GRANT statement New in SQL 2005 CREATE LOGIN statement CREATE USER statement
56
CREATE Database CREATE DATABASE [SQLClass] ON ( NAME = 'SQLClass',
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\SQLClass.mdf' , SIZE = 1, FILEGROWTH = 10%) LOG ON ( NAME = 'SQLClass_log', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\data\SQLClass_log.LDF' , COLLATE SQL_Latin1_General_CP1_CI_AS CREATE DATABASE database_name [ ON [ < filespec > [ ,...n ] ] [ , < filegroup > [ ,...n ] ] ] [ LOG ON { < filespec > [ ,...n ] } ] [ COLLATE collation_name ] [ FOR LOAD | FOR ATTACH ] < filespec > ::= [ PRIMARY ] ( [ NAME = logical_file_name , ] FILENAME = 'os_file_name' [ , SIZE = size ] [ , MAXSIZE = { max_size | UNLIMITED } ] [ , FILEGROWTH = growth_increment ] ) [ ,...n ] < filegroup > ::= FILEGROUP filegroup_name < filespec > [ ,...n ]
57
Setting Database Options
exec sp_dboption 'SQLClass', 'read only', 'false'
58
Create Table CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY (1, 1) NOT NULL , [Customer ] [varchar] (30) NULL , [CustomerState] [varchar] (5) NOT NULL ) ON [PRIMARY] GO CREATE TABLE [ database_name.[ owner ] . | owner. ] table_name ( { < column_definition > | column_name AS computed_column_expression | < table_constraint > ::= [ CONSTRAINT constraint_name ] } | [ { PRIMARY KEY | UNIQUE } [ ,...n ] ) [ ON { filegroup | DEFAULT } ] [ TEXTIMAGE_ON { filegroup | DEFAULT } ] < column_definition > ::= { column_name data_type } [ COLLATE < collation_name > ] [ [ DEFAULT constant_expression ] | [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ] ] [ ROWGUIDCOL] [ < column_constraint > ] [ ...n ] < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] [ WITH FILLFACTOR = fillfactor ] [ON {filegroup | DEFAULT} ] ] ] | [ [ FOREIGN KEY ] REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] [ NOT FOR REPLICATION ] ] | CHECK [ NOT FOR REPLICATION ] ( logical_expression ) } < table_constraint > ::= [ CONSTRAINT constraint_name ] { [ { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] { ( column [ ASC | DESC ] [ ,...n ] ) } [ WITH FILLFACTOR = fillfactor ] [ ON { filegroup | DEFAULT } ] ] | FOREIGN KEY [ ( column [ ,...n ] ) ] REFERENCES ref_table [ ( ref_column [ ,...n ] ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] [ NOT FOR REPLICATION ] | CHECK [ NOT FOR REPLICATION ] ( search_conditions ) }
59
Creating Other Objects
View Stored Procedure User Defined Function(UDF) Datatype
60
Alter Database Add/remove data and log files Alter properties of files
ALTER DATABASE Test1 MODIFY FILE ( NAME = test1dat3, SIZE = 20MB ) Alter filenames and locations ALTER DATABASE database { ADD FILE < filespec > [ ,...n ] [ TO FILEGROUP filegroup_name ] | ADD LOG FILE < filespec > [ ,...n ] | REMOVE FILE logical_file_name | ADD FILEGROUP filegroup_name | REMOVE FILEGROUP filegroup_name | MODIFY FILE < filespec > | MODIFY NAME = new_dbname | MODIFY FILEGROUP filegroup_name {filegroup_property | NAME = new_filegroup_name } | SET < optionspec > [ ,...n ] [ WITH < termination > ] | COLLATE < collation_name > } < filespec > ::= ( NAME = logical_file_name [ , NEWNAME = new_logical_name ] [ , FILENAME = 'os_file_name' ] [ , SIZE = size ] [ , MAXSIZE = { max_size | UNLIMITED } ] [ , FILEGROWTH = growth_increment ] ) < optionspec > ::= < state_option > | < cursor_option > | < auto_option > | < sql_option > | < recovery_option > < state_option > ::= { SINGLE_USER | RESTRICTED_USER | MULTI_USER } | { OFFLINE | ONLINE } | { READ_ONLY | READ_WRITE } < termination > ::= ROLLBACK AFTER integer [ SECONDS ] | ROLLBACK IMMEDIATE | NO_WAIT < cursor_option > ::= CURSOR_CLOSE_ON_COMMIT { ON | OFF } | CURSOR_DEFAULT { LOCAL | GLOBAL } < auto_option > ::= AUTO_CLOSE { ON | OFF } | AUTO_CREATE_STATISTICS { ON | OFF } | AUTO_SHRINK { ON | OFF } | AUTO_UPDATE_STATISTICS { ON | OFF } < sql_option > ::= …
61
Alter Table Adding fields – last position only Adding a primary key
ALTER TABLE table { [ ALTER COLUMN column_name { new_data_type [ ( precision [ , scale ] ) ] [ COLLATE < collation_name > ] [ NULL | NOT NULL ] | {ADD | DROP } ROWGUIDCOL } ] | ADD { [ < column_definition > ] | column_name AS computed_column_expression } [ ,...n ] | [ WITH CHECK | WITH NOCHECK ] ADD { < table_constraint > } [ ,...n ] | DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ] | { CHECK | NOCHECK } CONSTRAINT { ALL | constraint_name [ ,...n ] } | { ENABLE | DISABLE } TRIGGER { ALL | trigger_name [ ,...n ] } } < column_definition > ::= { column_name data_type } [ [ DEFAULT constant_expression ] [ WITH VALUES ] | [ IDENTITY [ (seed , increment ) [ NOT FOR REPLICATION ] ] ] [ ROWGUIDCOL ] [ < column_constraint > ] [ ...n ] < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL | NOT NULL ] | [ { PRIMARY KEY | UNIQUE } [ CLUSTERED | NONCLUSTERED ] [ WITH FILLFACTOR = fillfactor ] [ ON { filegroup | DEFAULT } ] | [ [ FOREIGN KEY ] REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE | NO ACTION } ] [ ON UPDATE { CASCADE | NO ACTION } ] [ NOT FOR REPLICATION ] | CHECK [ NOT FOR REPLICATION ] ( logical_expression ) …
62
Managing Database Size
Microsoft SQL Server Management Studio – recommended method Scripts DBCC SHRINKDATABASE ( database_name [ , target_percent ] [ , { NOTRUNCATE | TRUNCATEONLY } ] )
63
DROP Statement Destroys object forever Object can not be in use
Examples: DROP TABLE Customers DROP PROC pr_salesreport
64
Reverse-Scripting Objects
65
Information Schema Views
ANSI SQL method for extracting metadata Implemented as a set of views in MS SQL Information_schema.tables Information_schema.columns
66
Chapter 6: Constraints
67
Constraint Types Domain Entity Referential Integrity
68
Key Constraints Primary Key Foreign Key Unique
69
Constraint Scope Column Level Table Level
CREATE TABLE [dbo].[Customers] ( [CustomerID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY , [Customer ] [varchar] (30) NULL , [CustomerState] [varchar] (5) NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[Products] ADD CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ( [ProductID], [ProductName] ) ON [PRIMARY] GO
70
Check Constraints ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [CK_Products_No_Nissan] CHECK ([Productname] <> 'nissan sentra')
71
Default Constraints
72
Disabling Constraints
Bad Data During Constraint Creation? ALTER TABLE [dbo].[Products] WITH NOCHECK ADD CONSTRAINT [CK_Products_No_Nissan] CHECK ([Productname] <> 'nissan sentra') Temporarily During Data Load ALTER TABLE Products NOCHECK CONSTRAINT CK_Products_No_Nissan
73
Other Data Integrity Objects
Rule Object Default Object Non-ansi, outdated
74
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
75
Chapter 7 : Scripts and Batches
76
Scripts Text file containing one or more batches
Can make use of local variables or system functions like
77
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
78
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
79
Using EXEC Allows dynamic execution of an SQL string
Cannot reference local variables, only the string variable it is using System vars like still resolve Concatenation should be done in a variable before passing it to EXEC Cannot be used in a UDF
80
Chapter 8: Views
81
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
82
Creating Views CREATE VIEW TopSellers AS SELECT TOP 10 * FROM PRODUCTS
ORDER BY ItemsSold CREATE VIEW [ < database_name > . ] [ < owner > . ] view_name [ ( column [ ,...n ] ) ] [ WITH < view_attribute > [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] < view_attribute > ::= { ENCRYPTION | SCHEMABINDING | VIEW_METADATA }
83
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
84
Performance Views on Views reduce performance
Enterprise Edition allows performance gains: Indexed Views Partitioned Views Indexes on base tables are used
85
Security Can be used to hide sensitive data Ownership chain evaluation
86
Dropping Views Schema binding prevents dropping dependent objects
87
Lab 8A: Creating and Using Views
88
Chapter 9: Stored Procedures
89
Basic Syntax
90
Types of sprocs System stored procedure: Local stored procedure:
Name begins with sp_ Created in master database Intention is for application in any database Often used by sysadmins Local stored procedure: Defined in the local database Name often starts with pr_
91
Executing an sproc EXEC pr_GetTopProducts
92
Parameters @param as datatype = default [OUT]
93
Executing an sproc with parameters
By Name: EXEC pr_GetTopProducts @StartID = = 10 By Position: EXEC pr_GetTopProducts 1, 10 Leveraging Default values EXEC
94
Order of parameters Place parameters with default values at the end of the list for flexibility of use
95
Output parameters Used to send non-recordset information back to client Procedural insert example, which returns identity field
96
Error checking and data validation
Sprocs that modify data can conditionally check the data first
97
Return Used to return the success/failure status of the sproc
The return statement halts all other execution
98
Raising errors RAISERROR(‘demo error’, 1, 1)
99
Extended Stored Procs Xp_cmdshell ‘dir’
100
Debugging
101
Chapter 10: User Defined Functions
102
Basic Syntax CREATE FUNCTION dbo.fn_total(@param1 datatype)
RETURNS datatype2 AS BEGIN datatype2 here END
103
3 Types Scalar Inline table values Multi-statement table valued
Returns a single value Evaluated for every row if used in select line Inline table values Returns a variable of type table Single select statement defines the table Multi-statement table valued Multiple statements populate table values
104
Uses of Functions Can greatly simplify the select line
Can improve reliablility of data by reducing the number of joins and encapsulating queries Good choice for summarizing transactional data
105
UDF Considerations Can not use non-deterministic functions like getdate(), which depends on system settings to provide output Must use two part name
106
Creating System Functions
Create the function in master database Change the owner to system_function_schema: sp_changeobjectowner 'fn_somefunc2', 'system_function_schema'
107
Chapter 11:Triggers
108
Basic Syntax CREATE TRIGGER trg_one ON tablename
FOR INSERT, UPDATE, DELETE AS BEGIN SELECT * FROM Inserted SELECT * FROM Deleted END
109
Uses of triggers No change of front end code is required to perform:
Automation Notification Logging/Auditing Maintaining de-normalized data
110
Trigger Types For or After Instead Of
Synonymous – Operates at the end of the transaction, in addition to the data change operation Instead Of Operates in place of the data change command
111
DML INSERT, UPDATE & DELETE DDL On creation/deletion of objects
112
Trigger Considerations
“Inserted” table “Deleted” table Ater trigger participates in the transaction Can rollback any data changes if needed User needs permissions on any object hit by the trigger
113
Chapter 12: Cursors
114
Record Operations vs. Set Operations
115
Cursor Types Sensitivity to database changes Dynamic Keyset Static
Yes – all changes, but most overhead Keyset Yes, but only for updates and deletes Static No-Runs from a copy in TempDB
116
Basic Syntax DECLARE demo_cursor CURSOR READ_ONLY
FOR SELECT ProductID FROM Northwind..Products ORDER BY ProductID nvarchar(50) OPEN demo_cursor FETCH NEXT FROM demo_cursor WHILE <> -1) BEGIN IF <> -2) varchar(100) = 'The product is: ' END CLOSE demo_cursor DEALLOCATE demo_cursor GO
117
Cursor Options GLOBAL/LOCAL STATIC KEYSET DYNAMIC FAST FORWARD
118
The Fetch Statement NEXT PRIOR FIRST LAST ABSOLUTE RELATIVE
119
@@Fetch_Status -2 Means row was deleted -1 Means past the last row
Global to all cursors on the current connection
120
Returns number of rows available for the last cursor that was opened on this connection Returns -1 if cursor is dynamic
121
Performance Issues Avoid Cursors when possible
Consider client-side processing in lieu of cursors
122
Chapter 13: Transactions and Locks
123
Concurrency Problems Lost Updates Dirty Reads Nonrepeatable Reads
Two transactions select the same row, then update the row based on the values selected. The last one to save wins. Dirty Reads One transaction selects data from another uncommited(unfinished) update Nonrepeatable Reads Select statement of the same data returns different values because another transaction has changed the data between reads Phantom Reads Update or delete is performed on a set when another transaction is performing and insert or delete than affects a row in the set
124
Transaction Isolation Level
READ UNCOMMITTED Allows all concurrency problems READ COMMITTED Default. Prevents dirty reads. REPEATABLE READ Only allows phantom reads. SNAPSHOT New in Uses row versioning feature to store a copy of the data in TempDB database. Like serializable with less locking problems. SERIALIZABLE Safest, most locking timeout issues
125
Modifiying the transaction isolation level
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
126
Lockable Resources Database Allocation Unit Metadata File Table
Collection of pages Metadata File Table Heap or B-tree Extent Page Key Row
127
Lock Modes Shared Locks Exclusive Locks Schema Stability (Sch-S)
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)
128
Basic Transaction Syntax
BEGIN TRAN [tranname] --Multiple data edits here If = 0 COMMIT TRAN Else ROLLBACK TRAN
129
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
130
Managing locks Sp_who2 Sp_lock
131
Chapter 14: .Net/CLR Integration
132
Definitions CLR Assembly Common Language Runtime Compiled .Net Code
Manages Security Manages Memory and Cleanup of Resources Assembly Compiled .Net Code .dll .exe Houses Classes with Methods and Properties
133
CLR Objects in SQL Server
Stored Procedures Functions Triggers Aggregate Functions(UDA)* User-Defined Types* Can perform validation Provides for Methods and Types *No builtin SQL equivalent
134
When to Use CLR Objects Performance is not paramount
To perform tasks not available in SQL Leverage a class library Stats Mathmatics Encryption When it works better for you
135
Enabling CLR Or EXEC RECONFIGURE WITH OVERRIDE
136
Adding CLR Objects with Visual Studio
Visual Studio Express – CLR projects not supported
137
CLR Behind the Scenes Compile the code into an assembly
csc /target:library sp1.cs /r:"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlaccess.dll" Use CREATE ASSEMBLY CREATE ASSEMBLY CLRAssembly FROM 'C:\tmp\Sp1.dll' WITH PERMISSION_SET = SAFE Use CREATE PROC CREATE PROC EchoCLR @Message NVARCHAR(255) AS EXTERNAL NAME CLRAssembly.[Sp1].Echo GO
138
Chapter 15: SQL 2005/TSQL Extensions
139
Common Table Expressions
CTE’s are an ANSI 1999 Standard WITH clause used as a preface for SELECT, INSERT, UPDATE or DELETE Like a “Temporary View” CTE Always Produces a Set of Rows and the Names of Columns for Those Rows
140
Simple CTE Example WITH pi(constant) AS ( SELECT 3.14159265358979 )
SELECT constant FROM pi
141
CTE Heirarchical Example
CREATE TABLE Employees ( EmployeeID int primary key nonclustered, EmployeeName varchar(50), ManagerID int CONSTRAINT FK_ManagerID FOREIGN KEY References Employees(EmployeeID) )
142
CTE Heirarchical Example
--EmployeeID 1 is the boss INSERT employees(EmployeeID, EmployeeName, ManagerID) VALUES(1,'Andrew',1) --Reports to EmployeeID 1 VALUES(2,'Dave',1) VALUES(3,'Anne',1) --Reports to EmployeeID 3 VALUES(4,'Alex',3) VALUES(5,'Sandy',3)
143
CTE Heirarchical Example
CREATE FUNCTION int) RETURNS int AS BEGIN int; WITH Reports(EmployeeID) ( SELECT EmployeeID FROM Employees WHERE ManagerID AND EmployeeID <> 1 UNION ALL SELECT e.EmployeeID FROM Employees e INNER JOIN Reports r ON r.EmployeeID = e.ManagerID ) FROM Reports END
144
CTE Heirarchical Example
select employeename, Subordinates=dbo.SubordinateCount(employeeid) from employees employeename Subordinates Andrew Dave Anne Alex Sandy
145
.NET Extensions Code can be compiled to an assembly, then referenced in an SQL query Applies to functions, stored procedures, triggers, aggregate functions, user-defined datatypes(classes)
146
MARS Multiple Active Result Sets
Applies only to SQL Server 2005 and ADO.NET 2.0(SQL Native Client)
147
Service Broker Allows for asynchronous execution of queries
148
Try Catch syntax BEGIN TRY EXEC sp_ProcThatCallsRaiserror END TRY
BEGIN CATCH PRINT ‘Exception Occurred’ END CATCH
149
RowNumber() SELECT Result=row_number()
OVER(order by employeename asc), EmployeeName, Subordinates=dbo.reports(employeeid) FROM employees Result employeename Subordinates Alex Andrew Anne Dave Sandy
150
OUTPUT clause CREATE TABLE DeletedEmployeeIDs ( employeeid int )
DELETE Employees OUTPUT deleted.EmployeeID INTO DeletedEmployeeIDs
151
PIVOT Clause SELECT * FROM SALES
CREATE TABLE SALES ( [Year] INT, Quarter CHAR(2), Amount FLOAT ) INSERT INTO SALES VALUES (2001, 'Q2', 70) INSERT INTO SALES VALUES (2001, 'Q3', 55) INSERT INTO SALES VALUES (2001, 'Q3', 110) SELECT * FROM SALES PIVOT (SUM (Amount) — Aggregate the Amount column using SUM FOR [Quarter] — Pivot the Quarter column into column headings IN (Q1, Q2, Q3, Q4)) — use these quarters AS P Year Q1 Q2 Q3 Q4 ——- ——— ——— -—— ———
152
XML DataType
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.