+ All Categories
Home > Documents > SQL Server 2008 Trainning

SQL Server 2008 Trainning

Date post: 04-Apr-2018
Category:
Upload: yudhi-kurniawan
View: 214 times
Download: 0 times
Share this document with a friend

of 48

Transcript
  • 7/29/2019 SQL Server 2008 Trainning

    1/48

    SQL SERVER 2008Yudhi Kurniawan

  • 7/29/2019 SQL Server 2008 Trainning

    2/48

    Topics Views

    Stored Procedures

    User Defined Functions Triggers

  • 7/29/2019 SQL Server 2008 Trainning

    3/48

    Views A view is a virtual table that consists of columns

    from one or more tables

    Implements a security mechanism

    Complex queries can be stored in the

    form as a view, and data from the

    view can be extracted

    using simple queries

  • 7/29/2019 SQL Server 2008 Trainning

    4/48

    T-SQL View

    iewsCREATE VIEW [owner.]view_name

    [(column_name [, column_name]...)][WITH ENCRYPTION]S select_statement [WITH CHECK OPTION]

  • 7/29/2019 SQL Server 2008 Trainning

    5/48

    SQL Server stores information on the view in the following system tables:

    o SYSOBJECTS stores the name of the view.o SYSCOLUMNS stores the names of the columns defined in theview.o SYSDEPENDS stores information on the view dependencies.o SYSCOMMENTS stores the text of the view definition.

    o Views can have up to 1024 columns.o WITH ENCRYPTION encrypts the text for the view in theSYSCOMMENTS tables

  • 7/29/2019 SQL Server 2008 Trainning

    6/48

    The restrictions imposed on views are as follows A view can be created only in the current database.

    The name of a view must not be the same as that of the basetable they must follow the rules for identifiers.

    A view can be created only if there is a SELECT permissionon its base table.

    A SELECT INTO statement cannot be used in viewdeclaration statement.

    The CREATE VIEW statement cannot be combined withother SQL statements in a single batch.

  • 7/29/2019 SQL Server 2008 Trainning

    7/48

    SCHEMABINDING Binds views to underlying tables.

    The view may have to be modified or dropped to removedependency on table

    If a view is not created with schemabinding clausesp_refreshview should be run when underlying tablechanges.

  • 7/29/2019 SQL Server 2008 Trainning

    8/48

    WITH CHECK OPTION is an optional clause on the CREATE

    VIEW statement that specifies the level of checking to be done

    when inserting or updating data through a view. If the option isspecified, every row that is inserted or updated through the viewmust conform to the definition of that view

  • 7/29/2019 SQL Server 2008 Trainning

    9/48

    Alter Views

  • 7/29/2019 SQL Server 2008 Trainning

    10/48

    Drop Views

    When a view is dropped, it has no effect on the underlying tables.

    Dropping a view removes its definition and all the permissionsassigned to it.

    However, dropping a table that references a view does not drop the

    view automatically. You must drop it explicitly.

  • 7/29/2019 SQL Server 2008 Trainning

    11/48

    Rename View You can rename a view without having to drop it. This

    ensures that the permissions on the view are not lost

  • 7/29/2019 SQL Server 2008 Trainning

    12/48

    Modifying Data using Views A view may be derived from multiple underlying tables

    A single data modification statement that affected both the underlyingtables is not permitted.

    You cannot modify the following of Columns using a view:

    Columns that are based on computed values. E.g. sum, avg

    Columns that are based on row aggregate functions. E.g. group by,having

    Columns based on built-in functions like numeric, string functions.

  • 7/29/2019 SQL Server 2008 Trainning

    13/48

    Optimizing performance using Views

    Indexed Views You can significantly improve performance by creating a unique clustered index on a

    view that involves complex processing of large quantities of data, such as aggregating orjoining many rows

    Aggregations can be precompiled and stored in the index to minimize expensivecomputations during query execution

    Unique clustered index is created on the view, the view's result set is materializedimmediately and persisted in physical storage in the database, saving the overhead ofperforming this costly operation at execution time.

    When to Use Indexed Views Because indexed views are more complex to maintain than indexes on base tables, you

    should use them only when the improved speed in retrieving the results outweighs theincreased overhead of data modifications.

    Indexing views is not a good idea in a high-volume OLTP system.

    Indexed views work best when the data is relatively static, and you need to process manyrows or the view will be referenced by many queries.

  • 7/29/2019 SQL Server 2008 Trainning

    14/48

    Indexed Views in SQL Server 2005 SQL Server 2005 contains many improvements for indexed views

    compared with SQL Server 2000.

    Scalar aggregates, including SUM and COUNT_BIG without GROUPBY.

    Scalar expressions and user-defined functions (UDFs) Common Language Runtime (CLR) types.

    User-defined types (UDTs)

    UDFs based on the CLR

    Database Tuning Advisor - recommends indexed views in addition torecommending indexes on base tables, and table and index

    partitioning strategies

  • 7/29/2019 SQL Server 2008 Trainning

    15/48

    Requirements for Indexed Views Set the ANSI_NULLS option to ON when you create the tables referenced by the view Set the ANSI_NULLS and QUOTED_IDENTIFIER options to ON prior to creating the

    view

    The view must only reference base tables, not any other views Base tables referenced by the view must be in the same database as the view and must

    have the same owner Create the view and any user-defined functions referenced in the view with the

    SCHEMABINDING option. This means that the underlying tables or other databaseobjects cannot be altered or dropped as long as the view or function exists.

    Reference all table names and user-defined functions with two-part names onlyfor

    example, "dbo.Customers" for the Customers table. Any functions used by the view must be deterministic, meaning that the function must

    always return the same result anytime it's called with the same set of input values. A unique clustered index must be created before any other indexes can be created on the

    view. Additional disk space will be required to hold the data defined by the indexed view.

  • 7/29/2019 SQL Server 2008 Trainning

    16/48

    The following Transact-SQL syntax elements are illegal in an indexedview The * syntax to specify all columns. Column names must be explicitly stated. Repeated columnsfor example, SELECT Col1, Col2, Col1 AS Col. However, you can re-

    use a column if it's part of a different expressionfor example, SELECT Col1, AVG(Col1),Col1 + Col2 AS Total

    Derived tables and sub queries ROWSET. UNION. OUTER JOINS OR SELF JOINS. TOP AND ORDER BY.

    DISTINCT. COUNT(*). USE COUNT_BIG(*) INSTEAD, which returns a big int data type is allowed. The following aggregate functions: AVG, MAX, MIN, STDEV, STDEVP, VAR. The definition of indexed view must be deterministic

    CREATE TABLE T(a int, b real, c as getdate(), d as a+b)CREATE VIEW VT WITH SCHEMABINDING AS SELECT a, b, c, d FROM dbo.T

    SELECT object_id('VT'), COLUMNPROPERTY(object_id('VT'),'d','IsPrecise')

  • 7/29/2019 SQL Server 2008 Trainning

    17/48

  • 7/29/2019 SQL Server 2008 Trainning

    18/48

    Examples

  • 7/29/2019 SQL Server 2008 Trainning

    19/48

    TSQL Stored Procedures Precompiled execution. SQL Server compiles each stored procedure

    once and then reutilizes the execution plan. This results in tremendousperformance boosts when stored procedures are called repeatedly.

    Reduced client/server traffic. Stored procedures can reduce long SQLqueries to a single line that is transmitted over the wire hence reduceclient server traffic.

    Efficient reuse of code and programming abstraction.

    Enhanced security controls. You can grant users permission to execute astored procedure.

  • 7/29/2019 SQL Server 2008 Trainning

    20/48

    Create / Alter Syntax

  • 7/29/2019 SQL Server 2008 Trainning

    21/48

    Rename Stored Procedure

    Drop Procedure

  • 7/29/2019 SQL Server 2008 Trainning

    22/48

    Execute Stored Procedure EXECUTE procedure_nameParameterized Procedures

  • 7/29/2019 SQL Server 2008 Trainning

    23/48

    Error Handling in Stored Procedure@@ERROR - This function is used to implement error handling code. It

    contains the error ID produced by the last SQL statement executed during a

    clients connection. When a statement executes successfully, @@ERRORcontains 0. To determine if a statement executes successfully, an IF statement isused to check the value of the function immediately after the target statementexecutes. It is imperative that @@ERROR be checked immediately after thetarget statement, because its value is reset when the next statement executessuccessfully

  • 7/29/2019 SQL Server 2008 Trainning

    24/48

    RAISERROR- The RAISERROR statement is used to produce an ad hoc errormessage or to retrieve a custom message that is stored in the sysmessages table.

  • 7/29/2019 SQL Server 2008 Trainning

    25/48

    Try..Catch BlockImplements error handling for Transact-SQL that is similar to the exception handling in the

    programming languages. A group of Transact-SQL statements can be enclosed in a TRY block.If an error occurs in the TRY block, control is passed to another group of statements that is

    enclosed in a CATCH block. TRYCATCH constructs can be nested. Either a TRY block or a CATCH block can contain

    nested TRYCATCH constructs.

    A TRY block must be immediately followed by an associated CATCH block. Including anyother statements between the END TRY and BEGIN CATCH statements generates a syntax

    error. A TRYCATCH construct cannot span multiple blocks of Transact-SQL statements. For

    example, a TRYCATCH construct cannot span two BEGINEND blocks of Transact-SQLstatements

  • 7/29/2019 SQL Server 2008 Trainning

    26/48

    In the scope of a CATCH block, the following system functions can be used to obtaininformation about the error that caused the CATCH block to be executed:

    ERROR_NUMBER() returns the number of the error.

    ERROR_SEVERITY() returns the severity.

    ERROR_STATE() returns the error state number.

    ERROR_PROCEDURE() returns the name of the stored procedure or trigger

    where the error occurred.

    ERROR_LINE() returns the line number inside the routine that caused the error.

    ERROR_MESSAGE() returns the complete text of the error message. The textincludes the values supplied for any substitutable parameters, such as lengths,object names, or times.

  • 7/29/2019 SQL Server 2008 Trainning

    27/48

  • 7/29/2019 SQL Server 2008 Trainning

    28/48

    User defined functions (UDF) Acts like a function in programming language. Can be

    parameterized and called any number of times.

    Faster execution, Reduces network traffic.

    The ability for a function to act like a table (for Inline table andMulti-statement table functions) gives developers the ability to

    break out complex logic into shorter and shorter code blocks. Three types of UDFs

    Scalar UDFs

    Inline Table valued UDFs

    Multi-statement table valued UDFs

  • 7/29/2019 SQL Server 2008 Trainning

    29/48

    Scalar UDFs UDF returns a scalar data type. Text, ntext, image,

    timestamp are not supported.

  • 7/29/2019 SQL Server 2008 Trainning

    30/48

  • 7/29/2019 SQL Server 2008 Trainning

    31/48

    Inline Table Valued UDFsAn Inline Table-Value user-defined function returns a table data type. Its an alternative to a

    view as the user-defined function can pass parameters into a T-SQL select command and

    in essence provide us with a parameterized, non-updateable view of the underlying tables

  • 7/29/2019 SQL Server 2008 Trainning

    32/48

    Multi-Statement Table valued UDFs A Multi-Statement Table-Value user-defined function returns a table

    and is also an exceptional alternative to a view.

    The ability to pass parameters into a T-SQL select command or agroup of them gives us the capability to create a parameterized, non-updateable view of the data in the underlying tables.

    Within the create function command you must define the tablestructure that is being returned.

    After creating this type of user-defined function, you can use it in theFROM clause of a T-SQL command unlike the behaviour found whenusing a stored procedure which can also return record sets.

  • 7/29/2019 SQL Server 2008 Trainning

    33/48

  • 7/29/2019 SQL Server 2008 Trainning

    34/48

    Limitations of UDFs UDF Prohibit Usage of Non-Deterministic Built-in Functions. However

    it is allowed in SQL Server 2008. UDF cannot Call Stored Procedure

    UDF have only access to Extended Stored Procedure. UDFs cannot make use of dynamic SQL or temporary tables within the

    code. Table variables are allowed though. UDF can not Return XML.

    UDF does not support SET options. UDF does not Support Error Handling

    TRY/CATCH,RAISEERROR or @@ERROR are not allowed inUDFs.

    UDF is allowed to modify the physical state of a database using INSERT,UPDATE or DELETE statements.

    UDF can be called through a SQL statement without using theEXECUTE statement.

    A UDF (any of the three variations - scalar, inline or multi-statement)cannot be used to return multiple result sets.

  • 7/29/2019 SQL Server 2008 Trainning

    35/48

    Triggers in SQL 2005 A trigger is a database object that is attachedto a table.

    The main difference between a trigger and a stored procedure is thatthe former is attached to a table and is only firedwhen an INSERT,UPDATE or DELETE occurs

    Guards against malicious inserts and updates.

    Three types of Triggers in SQL 2005

    Instead of Triggers After Triggers

    Data Definition Language Triggers

    DML triggers use the deleted and inserted logical (conceptual) tables. Triggers can allow cross table references, however check constraints

    allow column level constraints.

  • 7/29/2019 SQL Server 2008 Trainning

    36/48

    SQL Server 2000 provides four different ways to determinethe affects of the DML statements.

    The INSERTED and

    DELETED tables, popularly known as MAGIC TABLES update ()

    columns_updated()

    Magic Table does not contain the information about thecolumns of the data-type text, ntext, or image.

    Attempting to access these columns will cause an error.

  • 7/29/2019 SQL Server 2008 Trainning

    37/48

    update() function is used to find whether a particular columnhas been updated or not. This function is generally used for

    data checks. Returns a Boolean value.

  • 7/29/2019 SQL Server 2008 Trainning

    38/48

    Columns_Update() function returns a varbinary data type representation of the columnsupdated. This function return a hexadecimal values from which we can determine whichcolumns in the table have been updated.

    COLUMNS_UPDATED tests for UPDATE or INSERT actions performed on multiplecolumns To test for UPDATE or INSERT attempts on one column, use UPDATE().

  • 7/29/2019 SQL Server 2008 Trainning

    39/48

    AFTERTriggers Triggers that run afteran update, insert, or delete can be used in several

    ways: Triggers can update, insert, or delete data in the same or other

    tables. This is useful to maintain relationships between data or tokeep audit trail information.

    Triggers can check data against values of data in the rest of thetable or in other tables.

    Triggers can use user-defined functions to activate non-databaseoperations. This is useful, for example, for issuing alerts orupdating information outside the database.

    Can be specified only on tables not on views.

    AFTER trigger is a trigger that gets executed automatically before the

    transaction is committed or rolled back. settriggerorder priority can set for AFTER triggers .

  • 7/29/2019 SQL Server 2008 Trainning

    40/48

    A table can have severalAFTER triggers for each of the threetriggering actions i.e., INSERT, DELETE and UPDATE

    If a table has multiple AFTER triggers, then you can specifywhich trigger should be executed first and which trigger shouldbe executed last using the stored procedure sp_settriggerorder

  • 7/29/2019 SQL Server 2008 Trainning

    41/48

    Like stored procedures and views, triggers can also be encrypted.The trigger definition is then stored in an unreadable form. Onceencrypted, the definition of the trigger cannot be decrypted andcannot be viewed by anyone, including the owner of the triggeror the system administrator.

  • 7/29/2019 SQL Server 2008 Trainning

    42/48

  • 7/29/2019 SQL Server 2008 Trainning

    43/48

    INSTEAD OF TriggersINSTEAD OF triggers facilitates updating Views.

    A view or table can have only one INSTEAD OF trigger for each INSERT, UPDATE

    and DELETE events

  • 7/29/2019 SQL Server 2008 Trainning

    44/48

    DDL Triggers in 2005 DDL triggers are fired on DDL events like Create, Alter,

    Drop. schema_name cannot be specified for DDL or logon triggers.

    ALL

    Indicates that all triggers defined at the scope of the ON clause aredisabled

    DATABASE

    For a DDL trigger, indicates that trigger_namewas created or modifiedto execute with database scope

    ALL SERVER

    For a DDL trigger, indicates that trigger_namewas created or modifiedto execute with server scope.

  • 7/29/2019 SQL Server 2008 Trainning

    45/48

  • 7/29/2019 SQL Server 2008 Trainning

    46/48

    Why Triggers? If the database is de-normalized and requires an automated

    way to update redundant data contained in multiple tables If customized messages and complex error handling are

    required

    If a value in one table must be validated against a non-identical value in another table.

    Triggers are a powerful tool that can be used to enforce thebusiness rules automatically when the data is modified.Triggers can also be used to maintain the data integrity. Butthey are not to maintain data integrity. Triggers should be

    used to maintain the data integrity only if you are unable toenforce the data integrity using CONSTRAINTS, RULESand DEFAULTS.

    Triggers cannot be created on the temporary tables.

    i

  • 7/29/2019 SQL Server 2008 Trainning

    47/48

    DISABLE/ [ENABLE] TRIGGER Trigger_Name

    ON ALL SERVER;

    DISABLE TRIGGER Person.uAddress ONPerson.Address;

    DISABLE TRIGGER safety ON DATABASE ;

    DROP TRIGGER Trigger_Name ON ALLSERVER;

    DISABLE Trigger ALL ON ALL SERVER;

    Like stored procedures triggers can also beencrypted.

    Triggers can be nested up to 32 levels.

    More on Triggers

  • 7/29/2019 SQL Server 2008 Trainning

    48/48

    THANK YOU


Recommended