t sql refrences

Upload: ggbar

Post on 07-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 T SQL Refrences

    1/23

    DAY 11. Data Types, Temporary Tables 1 hr 24/01/20062. Operators and system functions with @@ 2 hrs 24/01/2006

    3. Flow Control statements 2 hrs 24/01/20064. DCL 1 hr 24/01/20065. Tasks related todays learning 2 hrs 24/01/2006

    Data TypesbigintInteger (whole number) data from -2^63 (-9223372036854775808) through 2^63-1(9223372036854775807). Storage size is 8 bytes.intInteger (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).Storage size is 4 bytes. The SQL-92 synonym for int is integer.smallintInteger data from -2^15 (-32,768) through 2^15 - 1 (32,767). Storage size is 2 bytes.tinyintInteger data from 0 through 255. Storage size is 1 byte.RemarksThe bigint data type is supported where integer values are supported. However, bigint is

    intended for special cases where the integer values may exceed the range supported by the intdata type. The int data type remains the primary integer data type in SQL Server.bigint fits between smallmoney and int in the data type precedence chart.Functions will return bigint only if the parameter expression is a bigint data type. SQL Server willnot automatically promote other integer data types (tinyint, smallint, and int) to bigint.BitInteger data type 1, 0, or NULL.RemarksColumns of type bit cannot have indexes on them.Microsoft SQL Server optimizes the storage used for bit columns. If there are 8 or fewer bitcolumns in a table, the columns are stored as 1 byte. If there are from 9 through 16 bit columns,they are stored as 2 bytes, and so on.

  • 8/4/2019 T SQL Refrences

    2/23

    NumericNumeric data types with fixed precision and scale.decimal[(p[, s])] and numeric[(p[, s])]Fixed precision and scale numbers. When maximum precision is used, valid values are from -10^38 +1 through 10^38 - 1. The SQL-92 synonyms for decimal are dec and dec(p, s).

    p (precision)Specifies the maximum total number of decimal digits that can be stored, both to the left and tothe right of the decimal point. The precision must be a value from 1 through the maximum

    precision. The maximum precision is 38.s (scale)Specifies the maximum number of decimal digits that can be stored to the right of the decimalpoint. Scale must be a value from 0 through p. The default scale is 0; therefore, 0

  • 8/4/2019 T SQL Refrences

    3/23

    number of days after January 1, 1900. The other 2 bytes store the number of minutes sincemidnight. Dates range from January 1, 1900, through June 6, 2079, with accuracy to the minute.

    char and varcharFixed-length (char) or variable-length (varchar) character data types.char[(n)]Fixed-length non-Unicode character data with length ofn bytes. n must be a value from 1 through8,000. Storage size is n bytes. The SQL-92 synonym for char is character.

    varchar[(n)]Variable-length non-Unicode character data with length of n bytes. n must be a value from 1through 8,000. Storage size is the actual length in bytes of the data entered, not n bytes. Thedata entered can be 0 characters in length. The SQL-92 synonyms for varchar are char varyingor character varying.RemarksWhen n is not specified in a data definition or variable declaration statement, the default length is1. When n is not specified with the CAST function, the default length is 30.Objects using char or varchar are assigned the default collation of the database, unless aspecific collation is assigned using the COLLATE clause. The collation controls the code page usedto store the character data.Sites supporting multiple languages should consider using the Unicode nchar or nvarchar datatypes to minimize character conversion issues. If you use char or varchar:

    Use char when the data values in a column are expected to be consistently close to the samesize.Use varchar when the data values in a column are expected to vary considerably in size.If SET ANSI_PADDING is OFF when CREATE TABLE or ALTER TABLE is executed, a char columndefined as NULL is handled as varchar.When the collation code page uses double-byte characters, the storage size is still n bytes.Depending on the character string, the storage size ofn bytes may be less than n characters.Unicode Character Stringsnchar and nvarcharCharacter data types that are either fixed-length (nchar) or variable-length (nvarchar) Unicodedata and use the UNICODE UCS-2 character set.nchar(n)Fixed-length Unicode character data of n characters. n must be a value from 1 through 4,000.

    Storage size is two times n bytes. The SQL-92 synonyms for nchar are national char and nationalcharacter.nvarchar(n)Variable-length Unicode character data of n characters. n must be a value from 1 through 4,000.Storage size, in bytes, is two times the number of characters entered. The data entered can be 0characters in length. The SQL-92 synonyms for nvarchar are national char varying and nationalcharacter varying.RemarksWhen n is not specified in a data definition or variable declaration statement, the default length is1. When n is not specified with the CAST function, the default length is 30.Use nchar when the data entries in a column are expected to be consistently close to the samesize.Use nvarchar when the data entries in a column are expected to vary considerably in size.

    Objects using nchar or nvarchar are assigned the default collation of the database, unless aspecific collation is assigned using the COLLATE clause.SET ANSI_PADDING OFF does not apply to nchar or nvarchar. SET ANSI_PADDING is always ON fornchar and nvarchar.sql_variantA data type that stores values of various SQL Server-supported data types, except text, ntext,image, timestamp, and sql_variant.sql_variant may be used in columns, parameters, variables, and return values of user-definedfunctions. sql_variant allows these database objects to support values of other data types.Table

  • 8/4/2019 T SQL Refrences

    4/23

    A special data type that can be used to store a result set for later processing. Its primary use isfor temporary storage of a set of rows, which are to be returned as the result set of a table-valuedfunction.RemarksFunctions and variables can be declared to be of type table. table variables can be used infunctions, stored procedures, and batches.Use table variables instead of temporary tables, whenever possible. table variables provide thefollowing benefits:

    A table variable behaves like a local variable. It has a well-defined scope, which is the function,stored procedure, or batch in which it is declared.Within its scope, a table variable may be used like a regular table. It may be applied anywhere atable or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However,table may not be used in the following statements:INSERT INTO table_variable EXEC stored_procedureSELECT select_list INTO table_variable statements.table variables are cleaned up automatically at the end of the function, stored procedure, orbatch in which they are defined.table variables used in stored procedures result in fewer recompilations of the stored proceduresthan when temporary tables are used.Transactions involving table variables last only for the duration of an update on the table variable.Thus, table variables require less locking and logging resources.

    Assignment operation between table variables is not supported. In addition, because tablevariables have limited scope and are not part of the persistent database, they are not impactedby transaction rollbacks.timestampA database-wide unique number that gets updated every time a row gets updated.uniqueidentifierA globally unique identifier (GUID).SYSTEM TABLESSQL Server stores the data defining the configuration of the server and all its tables in a specialset of tables known as system tables. Users should not query or update the system tables directlyunless there is no other way to get the data required by the application. Only SQL Server shouldreference the system tables in response to administration commands issued by users. The systemtables can change from version to version; applications referencing system tables directly may

    have to be rewritten before they can be upgraded to a newer version of SQL Server with adifferent version of the system tables. SQL Server exposes most of the information from thesystem tables through other means. For more information, see System Tables.Temporary TablesSQL Server supports temporary tables. These tables have names that start with a number sign(#). If a temporary table is not dropped when a user disconnects, SQL Server automatically dropsthe temporary table. Temporary tables are not stored in the current database; they are stored inthe tempdb system database.There are two types of temporary tables:Local temporary tablesThe names of these tables begin with one number sign (#). These tables are visible only to theconnection that created them.Global temporary tables

    The names of these tables begin with two number signs (##). These tables are visible to allconnections. If the tables are not dropped explicitly before the connection that created themdisconnects, they are dropped as soon as all other tasks stop referencing them. No new tasks canreference a global temporary table after the connection that created it disconnects. Theassociation between a task and a table is always dropped when the current statement completesexecuting; therefore, global temporary tables are usually dropped soon after the connection thatcreated them disconnects.Many traditional uses of temporary tables can now be replaced with variables that have the tabledata type.Deterministic or NondeterministicAll functions are deterministic or nondeterministic:

    http://hhobj_3.click%28%29/http://hhobj_3.click%28%29/
  • 8/4/2019 T SQL Refrences

    5/23

    Deterministic functions always return the same result any time they are called with a specific setof input values.Nondeterministic functions may return different results each time they are called with a specificset of input values.Whether a function is deterministic or nondeterministic is called the determinism of the function.For example, the DATEADD built-in function is deterministic because it always returns the sameresult for any given set of argument values for its three parameters. GETDATE is not deterministicbecause it is always invoked with the same argument, yet the value it returns changes each time

    it is executed.@@ERRORReturns the error number for the last Transact-SQL statement executed.Syntax @@ERRORReturn Types integerRemarksWhen Microsoft SQL Server completes the execution of a Transact-SQL statement, @@ERRORis set to 0 if the statement executed successfully. If an error occurs, an error message is returned.@@ERROR returns the number of the error message until another Transact-SQL statement isexecuted. You can view the text associated with an @@ERROR error number in the sysmessagessystem table.Because @@ERROR is cleared and reset on each statement executed, check it immediatelyfollowing the statement validated, or save it to a local variable that can be checked later.

    ROWCOUNTReturns the number of rows affected by the last statement.Syntax@@ROWCOUNTReturn Types integerRemarksThis variable is set to 0 by any statement that does not return rows, such as an IF statement.Returns the number of active transactions for the current connection.Syntax @@TRANCOUNTReturn Types integerRemarksThe BEGIN TRANSACTION statement increments @@TRANCOUNT by 1. ROLLBACK TRANSACTIONdecrements @@TRANCOUNT to 0, except for ROLLBACK TRANSACTION savepoint_name, which

    does not affect @@TRANCOUNT. COMMIT TRANSACTION or COMMIT WORK decrement@@TRANCOUNT by 1.@@IDENTITYReturns the last-inserted identity value.Syntax @@IDENTITY

    Return Types Numeric

    RemarksAfter an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the lastidentity value generated by the statement. If the statement did not affect any tables with identitycolumns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identityvalues, @@IDENTITY returns the last identity value generated. If the statement fires one or moretriggers that perform inserts that generate identity values, calling @@IDENTITY immediately afterthe statement returns the last identity value generated by the triggers. The @@IDENTITY value

    does not revert to a previous setting if the INSERT or SELECT INTO statement or bulk copy fails, orif the transaction is rolled back.@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return thelast value inserted into the IDENTITY column of a table.@@IDENTITYand SCOPE_IDENTITYwill return the last identity value generated in any table inthe current session. However, SCOPE_IDENTITY returns the value only within the current scope;@@IDENTITY is not limited to a specific scope.IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.IDENT_CURRENT returns the identity value generated for a specific table in any session and anyscope. For more information, see IDENT_CURRENT.IDENT_SEED

  • 8/4/2019 T SQL Refrences

    6/23

    Returns the seed value (returned as numeric(@@MAXPRECISION,0)) specified during the creationof an identity column in a table or a view that has an identity column.Syntax IDENT_SEED ( 'table_or_view' )

    Arguments 'table_or_view'

    Is an expression specifying the table or view to check for a valid identity seed value.table_or_view can be a character string constant enclosed in quotation marks, a variable, afunction, or a column name. table_or_view is char, nchar, varchar, or nvarchar.Return Types numeric

    IDENT_INCRReturns the increment value (returned as numeric(@@MAXPRECISION,0)) specified during thecreation of an identity column in a table or view that has an identity column.Syntax IDENT_INCR ( 'table_or_view' )

    Arguments 'table_or_view'

    Is an expression specifying the table or view to check for a valid identity increment value.table_or_view can be a character string constant enclosed in quotation marks, a variable, afunction, or a column name. table_or_view is char, nchar, varchar, or nvarchar.Return Types numericSET IDENTITY_INSERT

    Allows explicit values to be inserted into the identity column of a table.

    Syntax SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF }Operator PrecedenceWhen a complex expression has multiple operators, operator precedence determines thesequence in which the operations are performed. The order of execution can significantly affectthe resulting value.Operators have these precedence levels. An operator on higher levels is evaluated before anoperator on a lower level:+ (Positive), - (Negative), ~ (Bitwise NOT)* (Multiply), / (Division), % (Modulo)+ (Add), (+ Concatenate), - (Subtract)=, >, =, , !< (Comparison operators)^ (Bitwise Exlusive OR), & (Bitwise AND), | (Bitwise OR)NOT

    ANDALL, ANY, BETWEEN, IN, LIKE, OR, SOMEComparison Operators Modified by ANY, SOME, or ALLComparison operators that introduce a subquery can be modified by the keywords ALL or ANY.SOME is an SQL-92 standard equivalent for ANY.Subqueries introduced with a modified comparison operator return a list of zero or more valuesand can include a GROUP BY or HAVING clause. These subqueries can be restated with EXISTS.Using the > comparison operator as an example, >ALL means greater than every value--in otherwords, greater than the maximum value. For example, >ALL (1, 2, 3) means greater than 3. >ANYmeans greater than at least one value, that is, greater than the minimum. So >ANY (1, 2, 3)means greater than 1.For a row in a subquery with >ALL to satisfy the condition specified in the outer query, the valuein the column introducing the subquery must be greater than each value in the list of values

    returned by the subquery.Similarly, >ANY means that for a row to satisfy the condition specified in the outer query, thevalue in the column that introduces the subquery must be greater than at least one of the valuesin the list of values returned by the subquery.

    Note This example can be run many different ways, as long as the inner query returns only onevalue.USE pubs-- Option 1 using MAX in the inner querySELECT titleFROM titlesHAVING MAX(advance) > ALL

  • 8/4/2019 T SQL Refrences

    7/23

    WHERE advance > ALL(SELECT MAX(advance)FROM publishers INNER JOIN titles ON

    titles.pub_id = publishers.pub_idWHERE pub_name = 'Algodata Infosystems')

    -- Option 2 using GROUP BY and HAVING and no ALLUSE pubsSELECT titleFROM titlesGROUP BY titleHAVING MAX(advance) >

    (SELECT MAX(advance)FROM publishers INNER JOIN titles ON

    titles.pub_id = publishers.pub_idWHERE pub_name = 'Algodata Infosystems')

    The following query provides an example of a subquery introduced with a comparison operator

    modified by ANY. It finds the titles that received an advance larger than the minimum advanceamount paid by Algodata Infosystems.USE pubsSELECT titleFROM titlesWHERE advance > ANY

    (SELECT advanceFROM publishers INNER JOIN titlesON titles.pub_id = publishers.pub_id

    AND pub_name = 'Algodata Infosystems')Here is the result set:title---------------------------------------------------------------

    You Can Combat Computer Stress!The Gourmet MicrowaveBut Is It User Friendly?Secrets of Silicon ValleyComputer Phobic and Non-Phobic Individuals: Behavior VariationsLife Without FearOnions, Leeks, and Garlic: Cooking Secrets of the MediterraneanSushi, Anyone?WHILESets a condition for the repeated execution of an SQL statement or statement block. Thestatements are executed repeatedly as long as the specified condition is true. The execution ofstatements in the WHILE loop can be controlled from inside the loop with the BREAK andCONTINUE keywords.

    SyntaxWHILE Boolean_expression

    { sql_statement | statement_block }[ BREAK ]{ sql_statement | statement_block }[ CONTINUE ]

    ArgumentsBoolean_expressionIs an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECTstatement, the SELECT statement must be enclosed in parentheses.{sql_statement| statement_block}

  • 8/4/2019 T SQL Refrences

    8/23

    Is any Transact-SQL statement or statement grouping as defined with a statement block. Todefine a statement block, use the control-of-flow keywords BEGIN and END.BREAKCauses an exit from the innermost WHILE loop. Any statements appearing after the END keyword,marking the end of the loop, are executed.CONTINUECauses the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.Remarks

    If two or more WHILE loops are nested, the inner BREAK exits to the next outermost loop. First, allthe statements after the end of the inner loop run, and then the next outermost loop restarts.When SET NOCOUNT is ON, the count (indicating the number of rows affected by a Transact-SQLstatement) is not returned. When SET NOCOUNT is OFF, the count is returned.The @@ROWCOUNT function is updated even when SET NOCOUNT is ON.When SET NOEXEC is ON, Microsoft SQL Server compiles each batch of Transact-SQLstatements but does not execute them. When SET NOEXEC is OFF, all batches are executed aftercompilation.The execution of statements in SQL Server consists of two phases: compilation and execution.This setting is useful for having SQL Server validate the syntax and object names in Transact-SQLcode when executing. It is also useful for debugging statements that would usually be part of alarger batch of statements.The setting of SET NOEXEC is set at execute or run time and not at parse time.

  • 8/4/2019 T SQL Refrences

    9/23

    DAY 21. working with tables and views, creating tables, renaming tables 1 hr

    25/01/2006

    2. Identity columns and operations 1 hr

    25/01/2006

    3. Relationship and Type of relations with task 1 hr

    25/01/2006

    4. Joins and SubQuery, join types and union operator 1 hr

    25/01/2006

    5. Select with all clauses, Null handling, Top, ROwCount, Aggregrate functions, 2 hrs

    25/01/2006

    6. using dynamic query, exec, sp_executesql and related tasks 2 hrs

    25/01/2006

  • 8/4/2019 T SQL Refrences

    10/23

    Partitioned ViewsA partitioned view is a view defined by a UNION ALL of member tables structured in the sameway, but stored separately as multiple tables in either the same SQL Server or in a group ofautonomous SQL Server 2000 serversUpdatable ViewsMicrosoft SQL Server 2000 enhances the class of updatable views in two ways:INSTEAD OF Triggers: INSTEAD OF triggers can be created on a view in order to make a viewupdatable. The INSTEAD OF trigger is executed instead of the data modification statement onwhich the trigger is defined. This trigger allows the user to specify the set of actions that need to

    take place in order to process the data modification statement. Thus, if an INSTEAD OF triggerexists for a view on a given data modification statement (INSERT, UPDATE, or DELETE), thecorresponding view is updatable through that statement. For more information about INSTEAD OFtriggers,Partitioned Views: If the view is of a specified form called 'partitioned view,' the view isupdatable, subject to certain restrictions. Partitioned views and their updatability are discussedlater in this topic.When needed, SQL Server will distinguish Local Partitioned Views as the views in which allparticipating tables and the view are on the same SQL Server, and Distributed PartitionedViews as the views in which at least one of the tables in the view resides on a different (remote)server.If a view does not have INSTEAD OF triggers, or if it is not a partitioned view, then it is updatableonly if the following conditions are satisfied:

    The select_statement has no aggregate functions in the select list and does not contain the TOP,GROUP BY, UNION (unless the view is a partitioned view as described later in this topic), orDISTINCT clauses. Aggregate functions can be used in a subquery in the FROM clause as long asthe values returned by the functions are not modified. For more information, seeselect_statement has no derived columns in the select list. Derived columns are result setcolumns formed by anything other than a simple column expression, such as using functions oraddition or subtraction operators.The FROM clause in the select_statementreferences at least one table. select_statementmusthave more than non-tabular expressions, which are expressions not derived from a table. Forexample, this view is not updatable:CREATE VIEW NoTable ASSELECT GETDATE() AS CurrentDate,

    @@LANGUAGE AS CurrentLanguage,

    CURRENT_USER AS CurrentUserINSERT, UPDATE, and DELETE statements also must meet certain qualifications before they canreference a view that is updatable, as specified in the conditions above. UPDATE and INSERTstatements can reference a view only if the view is updatable and the UPDATE or INSERTstatement is written so that it modifies data in only one of the base tables referenced in the FROMclause of the view. A DELETE statement can reference an updatable view only if the viewreferences exactly one table in its FROM clause.Table RelationshipsYou can create relationshipsbetween your tables in a database diagram to show how the columnsin one table are linked to columns in another table.In a relational database, relationships enable you to prevent redundant data. For example, if youare designing a database that will track information about books, you might have a table called

  • 8/4/2019 T SQL Refrences

    11/23

    titles that stores information about each book, such as the book's title, date of publication, andpublisher. There is also information you might want to store about the publisher, such as thepublisher's phone number, address, and zip code. If you were to store all of this information in thetitles table, the publisher's phone number would be duplicated for each title that the publisherprints.A better solution is to store the publisher information only once in a separate table, publishers.You would then put a pointer in the titles table that references an entry in the publisher table.To make sure your data is not out of sync, you can enforce referential integritybetween the titles

    and publishers tables. Referential integrity relationships help ensure information in one tablematches information in another. For example, each title in the titles table must be associated witha specific publisher in the publishers table. A title cannot be added to the database for a publisherthat does not exist in the database.For a better understanding of table relationships, see:Types of Table RelationshipsOverview of Referential IntegrityTypes of Table RelationshipsA relationship works by matching data in key columns usually columns with the same name inboth tables. In most cases, the relationship matches the primary key from one table, whichprovides a unique identifier for each row, with an entry in the foreign key in the other table. Forexample, sales can be associated with the specific titles sold by creating a relationship betweenthe title_id column in the titles table (the primary key) and the title_id column in the sales table

    (the foreign key).There are three types of relationships between tables. The type of relationship that is createddepends on how the related columns are defined.One-to-Many RelationshipsMany-to-Many RelationshipsOne-to-One RelationshipsOne-to-Many RelationshipsA one-to-many relationship is the most common type of relationship. In this type of relationship, arow in table A can have many matching rows in table B, but a row in table B can have only onematching row in table A. For example, the publishers and titles tables have a one-to-manyrelationship: each publisher produces many titles, but each title comes from only one publisher.A one-to-many relationship is created if only one of the related columns is a primary keyor has aunique constraint.

    The primary key side of a one-to-many relationship is denoted by a keysymbol. The foreign keyside of a relationship is denoted by an infinity symbol.Many-to-Many RelationshipsIn a many-to-many relationship, a row in table A can have many matching rows in table B, andvice versa. You create such a relationship by defining a third table, called a junction table, whoseprimary key consists of the foreign keys from both table A and table B. For example, the authorstable and the titles table have a many-to-many relationship that is defined by a one-to-manyrelationship from each of these tables to the titleauthors table. The primary key of the titleauthorstable is the combination of the au_id column (the authors table's primary key) and the title_idcolumn (the titles table's primary key).One-to-One RelationshipsIn a one-to-one relationship, a row in table A can have no more than one matching row in table B,and vice versa. A one-to-one relationship is created if both of the related columns are primary

    keys or have unique constraints.This type of relationship is not common because most information related in this way would be allin one table. You might use a one-to-one relationship to:Divide a table with many columns.Isolate part of a table for security reasons.Store data that is short-lived and could be easily deleted by simply deleting the table.Store information that applies only to a subset of the main table.

    The primary key side of a one-to-one relationship is denoted by a key symbol. The foreign

    key side is also denoted by a key symbol.

  • 8/4/2019 T SQL Refrences

    12/23

    Overview of Referential IntegrityReferential integrity is a system of rules that ensure relationships between rows in related tablesare valid and that you do not accidentally delete or change related data.When referential integrity is enforced, you must observe the following rules:You cannot enter a value in the foreign key column of the related table if that value does not existin the primary key of the related table. However, you can enter a null in the foreign key column.For example, you cannot indicate that a job is assigned to an employee who is not included in theemployee table, but you can indicate that an employee has no assigned job by entering a null in

    the job_id column of the employee table.You cannot delete a row from a primary key table if rows matching it exist in a related table. Forexample, you cannot delete a row from the jobstable if there are employees assigned to the jobrepresented by that row in the employeetable.You cannot change a primary key value in the primary key table if that row has related rows. Forexample, you cannot delete an employee from the employee table if that employee is assigned toa job in the jobs table.You can set referential integrity when all of the following conditions are met:The matching column from the primary table is a primary key or has a unique constraint.The related columns have the same data type and size.Both tables belong to the same database.SET ROWCOUNT.

    Causes Microsoft SQL Server to stop processing the query after the specified number of rowsare returned.Syntax SET ROWCOUNT { number | @number_var }Arguments number | @number_varIs the number (an integer) of rows to be processed before stopping the given query.RemarksIt is recommended that DELETE, INSERT, and UPDATE statements currently using SET ROWCOUNTbe rewritten to use the TOP syntax. For more information, see DELETE, INSERT, or UPDATE.The setting of the SET ROWCOUNT option is ignored for INSERT, UPDATE, and DELETE statementsagainst remote tables and local and remote partitioned views.To turn this option off (so that all rows are returned), specify SET ROWCOUNT 0.

    Note Setting the SET ROWCOUNT option causes most Transact-SQL statements to stopprocessing when they have been affected by the specified number of rows. This includes triggersand data modification statements such as INSERT, UPDATE, and DELETE. The ROWCOUNT optionhas no effect on dynamic cursors, but it limits the rowset of keyset and insensitive cursors. Thisoption should be used with caution and primarily with the SELECT statement.SET ROWCOUNT overrides the SELECT statement TOP keyword if the rowcount is the smallervalue.The setting of SET ROWCOUNT is set at execute or run time and not at parse time.

  • 8/4/2019 T SQL Refrences

    13/23

    DAY 3

    16 using dynamic query, exec, sp_executesql and related tasks 1 hr 25/01/200617 Data Integrity, Types Constraints, defaults, cascading, etc.. 2 hrs 26/01/200618 Stored Procedures , Error Handling, Nesting stored procedures 2 hr 26/01/200619 Cursors and it's types 1 hr 26/01/200620 Tasks realted todays work 2 hrs 26/01/2006

  • 8/4/2019 T SQL Refrences

    14/23

    Latching

    Latches are very lightweight, short-term synchronization objects protecting actions that need notbe locked for the life of a transaction. They are primarily used to protect a row when read for aconnection.When the relational engine is processing a query, each time a row is needed from a base table orindex, the relational engine uses the OLE DB API to request that the storage engine return therow. While the storage engine is actively transferring the row to the relational engine, the storageengine must ensure that no other task modifies either the contents of the row or certain pagestructures such as the page offset table entry locating the row being read. The storage enginedoes this by acquiring a latch, transferring the row in memory to the relational engine, and thenreleasing the latch.SQL Server Performance Monitor has a Latches object that indicates how many times latchescould not be granted immediately and the amount of time threads spent waiting for latches to begranted.

    ALTER PROCEDUREAlters a previously created procedure, created by executing the CREATE PROCEDURE statement,without changing permissions and without affecting any dependent stored procedures or triggers.For more information about the parameters used in the ALTER PROCEDURE statement, seeCREATE PROCEDURE.SyntaxALTER PROC [ EDURE ] procedure_name [ ; number ]

    [ { @parameter data_type }

    [ VARYING ] [ = default ] [ OUTPUT ]

    ] [ ,...n ]

    [ WITH

    { RECOMPILE | ENCRYPTION

    | RECOMPILE , ENCRYPTION

    }]

    [ FOR REPLICATION ]

    AS

    sql_statement [ ...n ]

    Using WAITFORThe WAITFOR statement suspends the execution of a connection until either:A specified time interval has passed.A specified time of day is reached.The WAITFOR statement is specified with one of two clauses: The DELAY keyword followed by an amount_of_time_to_pass before completing the WAITFORstatement. The time to wait before completing the WAITFOR statement can be up to 24 hours.The TIME keyword followed by a time_to_execute, which specifies completion of the WAITFOR

    statement.This example uses the DELAY keyword to wait for two seconds before performing a SELECTstatement:WAITFOR DELAY '00:00:02'SELECT EmployeeID FROM Northwind.dbo.EmployeesThis example uses the TIME keyword to wait until 10 P.M. to perform a check of the pubs specifieddatabase to make sure that all pages are correctly allocated and used:USE pubsBEGIN

    WAITFOR TIME '22:00'DBCC CHECKALLOC

    END

  • 8/4/2019 T SQL Refrences

    15/23

    The disadvantage of the WAITFOR statement is that the connection from the application remainssuspended until the WAITFOR completes. WAITFOR is best used when an application or storedprocedure must suspend processing for some relatively limited amount of time. Using SQL ServerAgent or SQL-DMO to schedule a task is a better method of executing an action at a specific timeof day.Comparing CHARINDEX and PATINDEXThe CHARINDEX and PATINDEX functions return the starting position of a pattern you specify.PATINDEX can use wildcard characters while CHARINDEX cannot.

    These functions take two parameters:The pattern whose position you want. With PATINDEX, the pattern is a literal string that cancontain wildcard characters. With CHARINDEX, the pattern is a literal string (no wildcardcharacters).A string-valued expression, usually a column name, in which Microsoft SQL Server searchesfor the specified pattern.For example, find the position at which the pattern "wonderful" begins in a certain row of thenotes column in the titles table.USE pubsSELECT CHARINDEX('wonderful', notes)FROM titlesWHERE title_id = 'TC3218'Here is the result set:

    ----------------46(1 row(s) affected)If you do not restrict the rows to be searched, the query returns all rows in the table and it reportsnonzero values for those rows in which the pattern was found, and zero for all others.For example, to use wildcards to find the position at which the pattern "candies" begins in anyrow of the Description column in the Categories table:USE NorthwindGOSELECT CategoryID, PATINDEX('%candies%', Description)AS POSITIONFROM CategoriesWHERE PATINDEX('%candies%', Description) 0If you do not restrict the rows to be searched, the query returns all rows in the table and reports

    nonzero values for those rows in which the pattern was found.PATINDEX is useful with text data types; it can be used in a WHERE clause in addition to IS NULL,IS NOT NULL, and LIKE (the only other comparisons that are valid on text in a WHERE clause).Stored procedures are nested when one stored procedure calls another. You can nest storedprocedures up to 32 levels. The nesting level increases by one when the called stored procedurebegins execution and decreases by one when the called stored procedure completes execution.Attempting to exceed the maximum of 32 levels of nesting causes the whole calling storedprocedure chain to fail. The current nesting level for the stored procedures in execution is storedin the @@NESTLEVEL function.Although the nesting limit is 32 levels, Microsoft SQL Server 2000 has no limit on the numberof stored procedures that can be invoked from a given stored procedure, provided that thesubordinate stored procedures do not invoke other subordinate stored procedures and themaximum nesting level is never exceeded.

    An error in a nested stored procedure is not necessarily fatal to the calling stored procedure.When invoking stored procedures within stored procedures, use the Transact-SQL RETURNstatement to return a return code and check the return code from the calling stored procedure. Inthis way, you can specify the behavior of your stored procedures when errors occur. For moreinformation about using return codes, see Returning Data Using a Return Code.Nesting Stored ProceduresStored procedures are nested when one stored procedure calls another. You can nest storedprocedures up to 32 levels. The nesting level increases by one when the called stored procedurebegins execution and decreases by one when the called stored procedure completes execution.Attempting to exceed the maximum of 32 levels of nesting causes the whole calling storedprocedure chain to fail. The current nesting level for the stored procedures in execution is storedin the @@NESTLEVEL function.

  • 8/4/2019 T SQL Refrences

    16/23

  • 8/4/2019 T SQL Refrences

    17/23

    Returns a user-defined error message and sets a system flag to record that an error has occurred.Using RAISERROR, the client can either retrieve an entry from the sysmessages table or build amessage dynamically with user-specified severity and state information. After the message isdefined it is sent back to the client as a server error message.SyntaxRAISERROR ( { msg_id | msg_str } { , severity , state }

    [ , argument [ ,...n ] ] )

    [ WITH option [ ,...n ] ]Argumentsmsg_idIs a user-defined error message stored in the sysmessages table. Error numbers for user-definederror messages should be greater than 50,000. Ad hoc messages raise an error of 50,000.msg_strIs an ad hoc message with formatting similar to the PRINTF format style used in C. The errormessage can have up to 400 characters. If the message contains more than 400 characters, onlythe first 397 will be displayed and an ellipsis will be added to indicate that the message has beencut. All ad hoc messages have a standard message ID of 14,000.This format is supported for msg_str:% [[flag] [width] [precision] [{h | l}]] typeThe parameters that can be used in msg_str are:

    flagIs a code that determines the spacing and justification of the user-defined error message.

    Code Prefix or justification Description- (minus) Left-justified Left-justify the result within the

    given field width.+ (plus) + (plus) or - (minus)

    prefixPreface the output value with a plus(+) or minus (-) sign if the outputvalue is of signed type.

    0 (zero) Zero padding If width is prefaced with 0, zeros areadded until the minimum width isreached. When 0 and - appear, 0 isignored. When 0 is specified with aninteger format (i, u, x, X, o, d), 0 is

    ignored.#(number)

    0x prefix for hexadecimaltype of x or X

    When used with the o, x, or Xformat, the # flag prefaces anynonzero value with 0, 0x, or 0X,respectively. When d, i, or u areprefaced by the # flag, the flag isignored.

    ' ' (blank) Space padding Preface the output value with blankspaces if the value is signed andpositive. This is ignored whenincluded with the plus sign (+) flag.

  • 8/4/2019 T SQL Refrences

    18/23

    DAY 4 & 5

    1. Triggers and types of triggers disableing nesting etc 3 hrs 27/01/2006

    2. Understaning existinf created triggers in Mailcentric 4 hrs 27/01/2006

    3. Tasks related triggers 1 hr 27/01/2006

    4. Functions , All system functions, math, string, datetime, etc.. 4 hrs 28/01/2006

    5. Creating user defined functions and tasks 4 hrs 28/01/2006

  • 8/4/2019 T SQL Refrences

    19/23

    CREATE TRIGGER

    Creates a trigger, which is a special kind of stored procedure that executes automatically when auser attempts the specified data-modification statement on the specified table. Microsoft SQLServer allows the creation of multiple triggers for any given INSERT, UPDATE, or DELETEstatement.

    Syntax

    CREATE TRIGGER trigger_nameON { table | view }[ WITH ENCRYPTION ]{

    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }[ WITH APPEND ][ NOT FOR REPLICATION ]AS[ { IF UPDATE ( column )

    [ { AND | OR } UPDATE ( column ) ][ ...n ]

    | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask ){ comparison_operator } column_bitmask [ ...n ]

    } ]sql_statement [ ...n ]

    }}

    Remarks

    Triggers are often used for enforcing business rules and data integrity. SQL Server providesdeclarative referential integrity (DRI) through the table creation statements (ALTER TABLE andCREATE TABLE); however, DRI does not provide cross-database referential integrity. To enforcereferential integrity (rules about the relationships between the primary and foreign keys oftables), use primary and foreign key constraints (the PRIMARY KEY and FOREIGN KEY keywords ofALTER TABLE and CREATE TABLE). If constraints exist on the trigger table, they are checked afterthe INSTEAD OF trigger execution and prior to the AFTER trigger execution. If the constraints areviolated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed(fired).

  • 8/4/2019 T SQL Refrences

    20/23

    The first and last AFTER triggers to be executed on a table may be specified by usingsp_settriggerorder. Only one first and one last AFTER trigger for each of the INSERT, UPDATE, andDELETE operations may be specified on a table; if there are other AFTER triggers on the sametable, they are executed randomly.

    If an ALTER TRIGGER statement changes a first or last trigger, the first or last attribute set on themodified trigger is dropped, and the order value must be reset with sp_settriggerorder.

    An AFTER trigger is executed only after the triggering SQL statement, including all referentialcascade actions and constraint checks associated with the object updated or deleted, hasexecuted successfully. The AFTER trigger sees the effects of the triggering statement as well asall referential cascade UPDATE and DELETE actions caused by the triggering statement.

    Trigger Limitations

    CREATE TRIGGER must be the first statement in the batch and can apply to only one table.

    A trigger is created only in the current database; however, a trigger can reference objects outsidethe current database.

    If the trigger owner name is specified (to qualify the trigger), qualify the table name in the sameway.

    The same trigger action can be defined for more than one user action (for example, INSERT andUPDATE) in the same CREATE TRIGGER statement.

    INSTEAD OF DELETE/UPDATE triggers cannot be defined on a table that has a foreign key with acascade on DELETE/UPDATE action defined.

    Any SET statement can be specified inside a trigger. The SET option chosen remains in effectduring the execution of the trigger and then reverts to its former setting.

    When a trigger fires, results are returned to the calling application, just as with stored procedures.To eliminate having results returned to an application due to a trigger firing, do not include eitherSELECT statements that return results, or statements that perform variable assignment in atrigger. A trigger that includes either SELECT statements that return results to the user orstatements that perform variable assignment requires special handling; these returned resultswould have to be written into every application in which modifications to the trigger table areallowed. If variable assignment must occur in a trigger, use a SET NOCOUNT statement at thebeginning of the trigger to eliminate the return of any result sets.

    A TRUNCATE TABLE statement is not caught by a DELETE trigger. Although a TRUNCATE TABLEstatement is, in effect, a DELETE without a WHERE clause (it removes all rows), it is not loggedand thus cannot execute a trigger. Because permission for the TRUNCATE TABLE statementdefaults to the table owner and is not transferable, only the table owner should be concerned

    about inadvertently circumventing a DELETE trigger with a TRUNCATE TABLE statement.

    The WRITETEXT statement, whether logged or unlogged, does not activate a trigger.

    These Transact-SQL statements are not allowed in a trigger:

    ALTER DATABASE CREATE DATABASE DISK INIT

    DISK RESIZE DROP DATABASE LOAD DATABASE

    LOAD LOG RECONFIGURE RESTORE DATABASE

  • 8/4/2019 T SQL Refrences

    21/23

    RESTORE LOG

    Note Because SQL Server does not support user-defined triggers on system tables, it isrecommended that no user-defined triggers be created on system tables.

    Multiple Triggers

    SQL Server allows multiple triggers to be created for each data modification event (DELETE,INSERT, or UPDATE). For example, if CREATE TRIGGER FOR UPDATE is executed for a table thatalready has an UPDATE trigger, then an additional update trigger is created. In earlier versions,only one trigger for each data modification event (INSERT, UPDATE, DELETE) was allowed for eachtable.

    Note The default behavior for CREATE TRIGGER (with the compatibility level of 70) is to addadditional triggers to existing triggers, if the trigger names differ. If trigger names are thesame, SQL Server returns an error message. However, if the compatibility level is equal to orless than 65, any new triggers created with the CREATE TRIGGER statement replace anyexisting triggers of the same type, even if the trigger names are different. For more

    information, see sp_dbcmptlevel.

    Recursive Triggers

    SQL Server also allows recursive invocation of triggers when the recursive triggers setting isenabled in sp_dboption.

    Recursive triggers allow two types of recursion to occur:

    Indirect recursion

    Direct recursion

    With indirect recursion, an application updates table T1, which fires trigger TR1, updating tableT2. In this scenario, trigger T2 then fires and updates table T1.

    With direct recursion, the application updates table T1, which fires trigger TR1, updating table T1.Because table T1 was updated, trigger TR1 fires again, and so on.

    This example uses both indirect and direct trigger recursion. Assume that two update triggers,TR1 and TR2, are defined on table T1. Trigger TR1 updates table T1 recursively. An UPDATEstatement executes each TR1 and TR2 one time. In addition, the execution of TR1 triggers theexecution of TR1 (recursively) and TR2. The inserted and deleted tables for a given triggercontain rows corresponding only to the UPDATE statement that invoked the trigger.

    Note The above behavior occurs only if the recursive triggers setting of sp_dboption isenabled. There is no defined order in which multiple triggers defined for a given event areexecuted. Each trigger should be self-contained.

    Disabling the recursive triggers setting only prevents direct recursions. To disable indirectrecursion as well, set the nested triggers server option to 0 using sp_configure.

    If any of the triggers do a ROLLBACK TRANSACTION, regardless of the nesting level, no furthertriggers are executed.

  • 8/4/2019 T SQL Refrences

    22/23

    Nested Triggers

    Triggers can be nested to a maximum of 32 levels. If a trigger changes a table on which there isanother trigger, the second trigger is activated and can then call a third trigger, and so on. If anytrigger in the chain sets off an infinite loop, the nesting level is exceeded and the trigger iscanceled. To disable nested triggers, set the nested triggers option of sp_configure to 0 (off). Thedefault configuration allows nested triggers. If nested triggers is off, recursive triggers is alsodisabled, regardless of the recursive triggers setting of sp_dboption.

    CONTAINS

    Is a predicate used to search columns containing character-based data types for precise or fuzzy(less precise) matches to single words and phrases, the proximity of words within a certaindistance of one another, or weighted matches. CONTAINS can search for:

    A word or phrase.

    The prefix of a word or phrase.

    A word near another word.

    A word inflectionally generated from another (for example, the word drive is theinflectional stem of drives, drove, driving, and driven).

    A word that has a higher designated weighting than another word.

    Syntax

    CONTAINS( { column | * } , '< contains_search_condition >'

    )

  • 8/4/2019 T SQL Refrences

    23/23