Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 SQL SERVER 2008 DEVELOPMENT 5 Day, Hands-On Course Author © David Ringsell 28/01/08.

Similar presentations


Presentation on theme: "1 SQL SERVER 2008 DEVELOPMENT 5 Day, Hands-On Course Author © David Ringsell 28/01/08."— Presentation transcript:

1

2 1 SQL SERVER 2008 DEVELOPMENT 5 Day, Hands-On Course Author © David Ringsell 28/01/08

3 2 2. LANGUAGE FEATURES zSQL Server Programming Tools zElements of Transact-SQL zSQL Server Object Names zAdditional Language Elements yLocal Variables yOperators yFunctions zWays to Execute Transact-SQL Statements zNew Transact-SQL (T-SQL) Features

4 3 SQL Server Programming Tools zSQL Server Management Studio yColor-codes syntax elements automatically yMultiple query windows yCustomizable views of result sets yGraphical execution plans yExecute portions of scripts zosql Utility yCommand-line utility

5 4 The Transact-SQL Programming Language zSQL Server Implementation of Entry-Level ANSI ISO Standard zCan Be Run on Any Entry-Level Compliant Product zContains Additional Unique Functionality

6 5 Elements of Transact-SQL zData Control Language Statements zData Definition Language Statements zData Manipulation Language Statements zSQL Server Object Names zNaming Guidelines

7 6 Data Control Language Statements zSet or Change Permissions yGRANT yDENY yREVOKE zBy Default, Only sysadmin, dbcreator, db_owner, and db_securityadmin Roles Can Execute

8 7 Data Definition Language Statements zDefine the Database Objects yCREATE object_type object_name yALTER object_type object_name yDROP object_type object_name

9 8 Data Manipulation Language Statements zUse When Working with Data in the Database ySELECT yINSERT yUPDATE yDELETE

10 9 SQL Server Object Names zStandard Identifiers yFirst character must be alphabetic yOther characters can include letters, numerals, or symbols yIdentifiers starting with symbols have special uses zDelimited Identifiers yUse when names contain embedded spaces yUse when reserved words are portions of names yEnclose in brackets ([ ]) or quotation marks (" ")

11 10 Naming Guidelines zUse Meaningful Names Where Possible zKeep Names Short zUse a Clear and Simple Naming Convention zChose an Identifier That Distinguishes Types of Objects yViews yStored procedures zKeep Object Names and User Names Unique

12 11 Additional Language Elements zLocal Variables zOperators zFunctions zFunction Examples zControl of Flow Language Elements zComments

13 12 Local Variables zUser-defined with DECLARE Statement zAssigned Values with SET or Select = 'Dodsworth' = FirstName FROM Northwind..Employees WHERE LastName + ' ' = 'Dodsworth' = FirstName FROM Northwind..Employees WHERE LastName + ' ' GO

14 13 Operators zTypes of Operators yArithmetic yComparison yString concatenation yLogical zOperator Precedence Levels

15 14 Functions Aggregate Functions Scalar Functions Rowset Functions SELECT * FROM OPENQUERY (OracleSvr, 'SELECT ENAME, EMPNO FROM SCOTT.EMP') SELECT AVG (UnitPrice) FROM Products SELECT DB_NAME() AS 'database'

16 15 Function Examples SELECT 'ANSI:' AS Region, CONVERT(varchar(30), GETDATE(), 102) AS Style UNION SELECT 'European:', CONVERT(varchar(30), GETDATE(), 113) UNION SELECT 'Japanese:', CONVERT(varchar(30), GETDATE(), 111) SELECT 'ANSI:' AS Region, CONVERT(varchar(30), GETDATE(), 102) AS Style UNION SELECT 'European:', CONVERT(varchar(30), GETDATE(), 113) UNION SELECT 'Japanese:', CONVERT(varchar(30), GETDATE(), 111) Result ANSI: European: Japanese: StyleStyle Mar :20:00: /03/22 Region

17 16 Control of Flow Language Elements zStatement Level yBEGIN…END blocks yIF…ELSE blocks yWHILE constructs zRow Level yCASE expression IF USER_NAME() <> 'dbo' BEGIN RAISERROR('Must be sysadmin to Perform Operation', 10, 1) RETURN END ELSE DBCC CHECKDB(Northwind) IF USER_NAME() <> 'dbo' BEGIN RAISERROR('Must be sysadmin to Perform Operation', 10, 1) RETURN END ELSE DBCC CHECKDB(Northwind)

18 17 Comments zIn-Line Comments zBlock Comments SELECT ProductName, (UnitsInStock + UnitsOnOrder) AS Max -- Calculates inventory, SupplierID FROM Products SELECT ProductName, (UnitsInStock + UnitsOnOrder) AS Max -- Calculates inventory, SupplierID FROM Products /* ** This code retrieves all rows of the products table ** and displays the unit price, the unit price increased ** by 10 percent, and the name of the product. */ SELECT UnitPrice, (UnitPrice * 1.1), ProductName FROM Products /* ** This code retrieves all rows of the products table ** and displays the unit price, the unit price increased ** by 10 percent, and the name of the product. */ SELECT UnitPrice, (UnitPrice * 1.1), ProductName FROM Products

19 18 Ways to Execute Transact- SQL Statements zDynamically Constructing Statements zUsing Batches zUsing Scripts zUsing Transactions zUsing XML

20 19 Dynamically Constructing Statements zUse EXECUTE with String Literals and Variables zUse When You Must Assign Value of Variable at Execution Time zAny Variables and Temporary Tables Last Only During Execution varchar(30) = 'Northwind' = 'Products' EXECUTE ('USE ' + ' SELECT * FROM varchar(30) = 'Northwind' = 'Products' EXECUTE ('USE ' + ' SELECT * FROM

21 20 Using Batches zOne or More Transact-SQL Statements Submitted Together zDefine a Batch by Using the GO Statement zHow SQL Server Processes Batches zYou Cannot Combine Some Statements in a Batch yCREATE PROCEDURE yCREATE VIEW yCREATE TRIGGER yCREATE RULE yCREATE DEFAULT

22 21 Using Scripts zContain Saved Statements zCan Be Written in Any Text Editor ySave by using.sql file name extension zExecute in SQL Query Analyzer or osql Utility zUse to Recreate Database Objects or to Execute Statements Repeatedly

23 22 Using Transactions zProcessed Like a Batch zData Integrity Is Guaranteed zChanges to the Database Are Either Applied Together or Rolled Back BEGIN TRANSACTION UPDATE savings SET amount = (amount - 100) WHERE custid = … UPDATE checking SET amount = (amount + 100) WHERE custid = … COMMIT TRANSACTION BEGIN TRANSACTION UPDATE savings SET amount = (amount - 100) WHERE custid = … UPDATE checking SET amount = (amount + 100) WHERE custid = … COMMIT TRANSACTION

24 23 New Transact-SQL (T-SQL) zCommon Table Expressions (CTE) yUseful for recursive queries zRanking Functions yRANK, DENSE_RANK, ROW_NUMBER, PARTITION BY zTOP(N) yN can be a parameter or expression zAPPLY yRun a query for each row and merge results zPIVOT yRotate data into row headings zFOR XML PATH yEasier control over XML result

25 24 Try/Catch Error Handling BEGIN TRY -- Statement with error END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS Number, ERROR_SEVERITY() AS Severity, ERROR_STATE() AS State, ERROR_PROCEDURE() AS procedureName, ERROR_LINE() AS Line, ERROR_MESSAGE() AS messageText; END CATCH

26 25 EXECUTE AS zUsed to specify security context under which stored procedure executes zWITH EXECUTE AS options: ySELF the user who created the stored procedure yOWNER the owner of the stored procedure y'user_name' a specified user name

27 26 Snapshot Isolation Level zNew isolation level for transactions zNo locks placed when reading data zNo dirty reads yAlways see the last committed values zUses tempdb to store row versions zCan significantly improve concurrency

28 27 Running CLR Code in SQL Server 2008 zOvercomes limitations of Transact-SQL by hosting the Common Language Runtime (CLR) zGood for processor-intensive code yTransact-SQL best for DML zUse a.NET Framework language to write: yStored procedures yUser-defined functions yTriggers yUser-defined types yAggregates

29 28 Recommended Practices Use ANSI SQL Syntax Keep Business Logic on the Server As Stored Procedures Save Statements As Scripts and Comment Them Thoroughly Format Transact-SQL Statements to Be Legible to Others Choose an Appropriate Naming Convention

30 29 2. REVIEW zSQL Server Programming Tools zElements of Transact-SQL zSQL Server Object Names zAdditional Language Elements yLocal Variables yOperators yFunctions zWays to Execute Transact-SQL Statements zNew Transact-SQL (T-SQL) Features

31 30 CHAPTER CONTENTS 1.SQL SERVER OVERVIEW 2.LANGUAGE FEATURES 3.DESIGN A DATABASE 4.IMPLEMENT TABLES 5.ACCESS AND MODIFY DATA 6.IMPLEMENT VIEWS 7.IMPLEMENT FUNCTIONS 8.IMPLEMENT TRIGGERS 9.IMPLEMENT STORED PROCEDURES 10.INDEXING TABLES 11.ACCESSING LINKED SERVERS 12.TRANSACTIONS AND LOCKS


Download ppt "1 SQL SERVER 2008 DEVELOPMENT 5 Day, Hands-On Course Author © David Ringsell 28/01/08."

Similar presentations


Ads by Google