Sie sind auf Seite 1von 23

DAY 1

1. Data Types, Temporary Tables 2. Operators and system functions with @@ 2 hrs 3. Flow Control statements 4. DCL 1 hr 5. Tasks related todays learning 1 hr 2 hrs 2 hrs 24/01/2006 24/01/2006 24/01/2006 24/01/2006 24/01/2006

Data Types bigint Integer (whole number) data from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807). Storage size is 8 bytes. int Integer (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. smallint Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). Storage size is 2 bytes. tinyint Integer data from 0 through 255. Storage size is 1 byte. Remarks The 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 int data 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 will not automatically promote other integer data types (tinyint, smallint, and int) to bigint. Bit Integer data type 1, 0, or NULL. Remarks Columns of type bit cannot have indexes on them. Microsoft SQL Server optimizes the storage used for bit columns. If there are 8 or fewer bit columns 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.

Numeric Numeric 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 to the 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 decimal point. Scale must be a value from 0 through p. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision. Precision Storage bytes Money 19 5 Monetary data types for representing monetary or 10-19 9 currency values. 20-28 13 money 29-38 17 Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. Storage size is 8 bytes. smallmoney Monetary data values from - 214,748.3648 through +214,748.3647, with accuracy to a tenthousandth of a monetary unit. Storage size is 4 bytes. float and real Approximate number data types for use with floating point numeric data. Floating point data is approximate; not all values in the data type range can be precisely represented. Syntax float [ ( n ) ] Is a floating point number data from - 1.79E + 308 through 1.79E + 308. n is the number of bits used to store the mantissa of the float number in scientific notation and thus dictates the precision and storage size. n must be a value from 1 through 53. n is Precision Storage size 1-24 7 digits 4 bytes 25-53 15 digits 8 bytes The Microsoft SQL Server float[(n)] data type conforms to the SQL-92 standard for all values of n from 1 to 53. The synonym for double precision is float(53). Real Floating point number data from 3.40E + 38 through 3.40E + 38. Storage size is 4 bytes. In SQL Server, the synonym for real is float(24). Datetime and smalldatetime Datetime Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of threehundredths of a second, or 3.33 milliseconds. Smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute. Remarks Values with the datetime data type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. The smalldatetime data type stores dates and times of day with less precision than datetime. SQL Server stores smalldatetime values as two 2-byte integers. The first 2 bytes store the

number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight. Dates range from January 1, 1900, through June 6, 2079, with accuracy to the minute. char and varchar Fixed-length (char) or variable-length (varchar) character data types. char[(n)] Fixed-length non-Unicode character data with length of n bytes. n must be a value from 1 through 8,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 1 through 8,000. Storage size is the actual length in bytes of the data entered, not n bytes. The data entered can be 0 characters in length. The SQL-92 synonyms for varchar are char varying or character varying. Remarks When n is not specified in a data definition or variable declaration statement, the default length is 1. 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 a specific collation is assigned using the COLLATE clause. The collation controls the code page used to store the character data. Sites supporting multiple languages should consider using the Unicode nchar or nvarchar data types 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 same size. 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 column defined 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 of n bytes may be less than n characters. Unicode Character Strings nchar and nvarchar Character data types that are either fixed-length (nchar) or variable-length (nvarchar) Unicode data 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 national character. 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 0 characters in length. The SQL-92 synonyms for nvarchar are national char varying and national character varying. Remarks When n is not specified in a data definition or variable declaration statement, the default length is 1. 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 same size. 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 a specific collation is assigned using the COLLATE clause. SET ANSI_PADDING OFF does not apply to nchar or nvarchar. SET ANSI_PADDING is always ON for nchar and nvarchar. sql_variant A 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-defined functions. sql_variant allows these database objects to support values of other data types. Table

A special data type that can be used to store a result set for later processing. Its primary use is for temporary storage of a set of rows, which are to be returned as the result set of a table-valued function. Remarks Functions and variables can be declared to be of type table. table variables can be used in functions, stored procedures, and batches. Use table variables instead of temporary tables, whenever possible. table variables provide the following 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 a table 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_procedure SELECT select_list INTO table_variable statements. table variables are cleaned up automatically at the end of the function, stored procedure, or batch in which they are defined. table variables used in stored procedures result in fewer recompilations of the stored procedures than 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 table variables have limited scope and are not part of the persistent database, they are not impacted by transaction rollbacks. timestamp A database-wide unique number that gets updated every time a row gets updated. uniqueidentifier A globally unique identifier (GUID). SYSTEM TABLES SQL Server stores the data defining the configuration of the server and all its tables in a special set of tables known as system tables. Users should not query or update the system tables directly unless there is no other way to get the data required by the application. Only SQL Server should reference the system tables in response to administration commands issued by users. The system tables 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 a different version of the system tables. SQL Server exposes most of the information from the system tables through other means. For more information, see System Tables. Temporary Tables SQL 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 drops the temporary table. Temporary tables are not stored in the current database; they are stored in the tempdb system database. There are two types of temporary tables: Local temporary tables The names of these tables begin with one number sign (#). These tables are visible only to the connection that created them. Global temporary tables The names of these tables begin with two number signs (##). These tables are visible to all connections. If the tables are not dropped explicitly before the connection that created them disconnects, they are dropped as soon as all other tasks stop referencing them. No new tasks can reference a global temporary table after the connection that created it disconnects. The association between a task and a table is always dropped when the current statement completes executing; therefore, global temporary tables are usually dropped soon after the connection that created them disconnects. Many traditional uses of temporary tables can now be replaced with variables that have the table data type. Deterministic or Nondeterministic All functions are deterministic or nondeterministic:

Deterministic functions always return the same result any time they are called with a specific set of input values. Nondeterministic functions may return different results each time they are called with a specific set 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 same result for any given set of argument values for its three parameters. GETDATE is not deterministic because it is always invoked with the same argument, yet the value it returns changes each time it is executed. @@ERROR Returns the error number for the last Transact-SQL statement executed. Syntax @@ERROR Return Types integer Remarks When Microsoft SQL Server completes the execution of a Transact-SQL statement, @@ERROR is 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 is executed. You can view the text associated with an @@ERROR error number in the sysmessages system table. Because @@ERROR is cleared and reset on each statement executed, check it immediately following the statement validated, or save it to a local variable that can be checked later. ROWCOUNT Returns the number of rows affected by the last statement. Syntax @@ROWCOUNT Return Types integer Remarks This 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 @@TRANCOUNT Return Types integer Remarks The BEGIN TRANSACTION statement increments @@TRANCOUNT by 1. ROLLBACK TRANSACTION decrements @@TRANCOUNT to 0, except for ROLLBACK TRANSACTION savepoint_name, which does not affect @@TRANCOUNT. COMMIT TRANSACTION or COMMIT WORK decrement @@TRANCOUNT by 1. @@IDENTITY Returns the last-inserted identity value. Syntax @@IDENTITY Return Types Numeric Remarks After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated. If the statement fires one or more triggers that perform inserts that generate identity values, calling @@IDENTITY immediately after the 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, or if the transaction is rolled back. @@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table. @@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the 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 any scope. For more information, see IDENT_CURRENT. IDENT_SEED

Returns the seed value (returned as numeric(@@MAXPRECISION,0)) specified during the creation of 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, a function, or a column name. table_or_view is char, nchar, varchar, or nvarchar. Return Types numeric IDENT_INCR Returns the increment value (returned as numeric(@@MAXPRECISION,0)) specified during the creation 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, a function, or a column name. table_or_view is char, nchar, varchar, or nvarchar. Return Types numeric SET 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 Precedence When a complex expression has multiple operators, operator precedence determines the sequence in which the operations are performed. The order of execution can significantly affect the resulting value. Operators have these precedence levels. An operator on higher levels is evaluated before an operator on a lower level: + (Positive), - (Negative), ~ (Bitwise NOT) * (Multiply), / (Division), % (Modulo) + (Add), (+ Concatenate), - (Subtract) =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators) ^ (Bitwise Exlusive OR), & (Bitwise AND), | (Bitwise OR) NOT AND ALL, ANY, BETWEEN, IN, LIKE, OR, SOME Comparison Operators Modified by ANY, SOME, or ALL Comparison 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 values and 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 other words, greater than the maximum value. For example, >ALL (1, 2, 3) means greater than 3. >ANY means 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 value in 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, the value in the column that introduces the subquery must be greater than at least one of the values in 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 one value. USE pubs -- Option 1 using MAX in the inner query SELECT title FROM titles HAVING MAX(advance) > ALL

WHERE advance > ALL ( SELECT MAX(advance) FROM publishers INNER JOIN titles ON titles.pub_id = publishers.pub_id WHERE pub_name = 'Algodata Infosystems' ) -- Option 2 using GROUP BY and HAVING and no ALL USE pubs SELECT title FROM titles GROUP BY title HAVING MAX(advance) > ( SELECT MAX(advance) FROM publishers INNER JOIN titles ON titles.pub_id = publishers.pub_id WHERE 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 advance amount paid by Algodata Infosystems. USE pubs SELECT title FROM titles WHERE advance > ANY (SELECT advance FROM publishers INNER JOIN titles ON titles.pub_id = publishers.pub_id AND pub_name = 'Algodata Infosystems') Here is the result set: title --------------------------------------------------------------You Can Combat Computer Stress! The Gourmet Microwave But Is It User Friendly? Secrets of Silicon Valley Computer Phobic and Non-Phobic Individuals: Behavior Variations Life Without Fear Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean Sushi, Anyone? WHILE Sets a condition for the repeated execution of an SQL statement or statement block. The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords. Syntax WHILE Boolean_expression { sql_statement | statement_block } [ BREAK ] { sql_statement | statement_block } [ CONTINUE ] Arguments Boolean_expression Is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses. {sql_statement | statement_block}

Is any Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block, use the control-of-flow keywords BEGIN and END. BREAK Causes an exit from the innermost WHILE loop. Any statements appearing after the END keyword, marking the end of the loop, are executed. CONTINUE Causes 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, all the 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-SQL statement) 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-SQL statements but does not execute them. When SET NOEXEC is OFF, all batches are executed after compilation. 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-SQL code when executing. It is also useful for debugging statements that would usually be part of a larger batch of statements. The setting of SET NOEXEC is set at execute or run time and not at parse time.

DAY 2
1. working with tables and views, creating tables, renaming tables 25/01/2006 2. Identity columns and operations 25/01/2006 3. Relationship and Type of relations with task 25/01/2006 4. Joins and SubQuery, join types and union operator 25/01/2006 5. Select with all clauses, Null handling, Top, ROwCount, Aggregrate functions, 25/01/2006 6. using dynamic query, exec, sp_executesql and related tasks 25/01/2006 2 hrs 2 hrs 1 hr 1 hr 1 hr 1 hr

Partitioned Views A partitioned view is a view defined by a UNION ALL of member tables structured in the same way, but stored separately as multiple tables in either the same SQL Server or in a group of autonomous SQL Server 2000 servers Updatable Views Microsoft 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 view updatable. The INSTEAD OF trigger is executed instead of the data modification statement on which 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 trigger exists for a view on a given data modification statement (INSERT, UPDATE, or DELETE), the corresponding view is updatable through that statement. For more information about INSTEAD OF triggers, Partitioned Views: If the view is of a specified form called 'partitioned view,' the view is updatable, subject to certain restrictions. Partitioned views and their updatability are discussed later in this topic. When needed, SQL Server will distinguish Local Partitioned Views as the views in which all participating tables and the view are on the same SQL Server, and Distributed Partitioned Views 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 updatable only 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), or DISTINCT clauses. Aggregate functions can be used in a subquery in the FROM clause as long as the values returned by the functions are not modified. For more information, see select_statement has no derived columns in the select list. Derived columns are result set columns formed by anything other than a simple column expression, such as using functions or addition or subtraction operators. The FROM clause in the select_statement references at least one table. select_statement must have more than non-tabular expressions, which are expressions not derived from a table. For example, this view is not updatable: CREATE VIEW NoTable AS SELECT GETDATE() AS CurrentDate, @@LANGUAGE AS CurrentLanguage, CURRENT_USER AS CurrentUser INSERT, UPDATE, and DELETE statements also must meet certain qualifications before they can reference a view that is updatable, as specified in the conditions above. UPDATE and INSERT statements can reference a view only if the view is updatable and the UPDATE or INSERT statement is written so that it modifies data in only one of the base tables referenced in the FROM clause of the view. A DELETE statement can reference an updatable view only if the view references exactly one table in its FROM clause. Table Relationships You can create relationships between your tables in a database diagram to show how the columns in one table are linked to columns in another table. In a relational database, relationships enable you to prevent redundant data. For example, if you are designing a database that will track information about books, you might have a table called

titles that stores information about each book, such as the book's title, date of publication, and publisher. There is also information you might want to store about the publisher, such as the publisher's phone number, address, and zip code. If you were to store all of this information in the titles table, the publisher's phone number would be duplicated for each title that the publisher prints. 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 integrity between the titles and publishers tables. Referential integrity relationships help ensure information in one table matches information in another. For example, each title in the titles table must be associated with a specific publisher in the publishers table. A title cannot be added to the database for a publisher that does not exist in the database. For a better understanding of table relationships, see: Types of Table Relationships Overview of Referential Integrity Types of Table Relationships A relationship works by matching data in key columns usually columns with the same name in both tables. In most cases, the relationship matches the primary key from one table, which provides a unique identifier for each row, with an entry in the foreign key in the other table. For example, sales can be associated with the specific titles sold by creating a relationship between the 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 created depends on how the related columns are defined. One-to-Many Relationships Many-to-Many Relationships One-to-One Relationships One-to-Many Relationships A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A. For example, the publishers and titles tables have a one-to-many relationship: 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 key or has a unique constraint. The primary key side of a one-to-many relationship is denoted by a keysymbol. The foreign key side of a relationship is denoted by an infinity symbol. Many-to-Many Relationships In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B. For example, the authors table and the titles table have a many-to-many relationship that is defined by a one-to-many relationship from each of these tables to the titleauthors table. The primary key of the titleauthors table is the combination of the au_id column (the authors table's primary key) and the title_id column (the titles table's primary key). One-to-One Relationships In 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 all in 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 key side is also denoted by a key symbol. symbol. The foreign

Overview of Referential Integrity Referential integrity is a system of rules that ensure relationships between rows in related tables are 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 exist in 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 the employee 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. For example, you cannot delete a row from the jobs table if there are employees assigned to the job represented by that row in the employee table. You cannot change a primary key value in the primary key table if that row has related rows. For example, you cannot delete an employee from the employee table if that employee is assigned to a 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 rows are returned. Syntax SET ROWCOUNT { number | @number_var } Arguments number | @number_var Is the number (an integer) of rows to be processed before stopping the given query. Remarks It is recommended that DELETE, INSERT, and UPDATE statements currently using SET ROWCOUNT be 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 statements against 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 stop processing when they have been affected by the specified number of rows. This includes triggers and data modification statements such as INSERT, UPDATE, and DELETE. The ROWCOUNT option has no effect on dynamic cursors, but it limits the rowset of keyset and insensitive cursors. This option should be used with caution and primarily with the SELECT statement. SET ROWCOUNT overrides the SELECT statement TOP keyword if the rowcount is the smaller value. The setting of SET ROWCOUNT is set at execute or run time and not at parse time.

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

Latching Latches are very lightweight, short-term synchronization objects protecting actions that need not be locked for the life of a transaction. They are primarily used to protect a row when read for a connection. When the relational engine is processing a query, each time a row is needed from a base table or index, the relational engine uses the OLE DB API to request that the storage engine return the row. While the storage engine is actively transferring the row to the relational engine, the storage engine must ensure that no other task modifies either the contents of the row or certain page structures such as the page offset table entry locating the row being read. The storage engine does this by acquiring a latch, transferring the row in memory to the relational engine, and then releasing the latch. SQL Server Performance Monitor has a Latches object that indicates how many times latches could not be granted immediately and the amount of time threads spent waiting for latches to be granted. ALTER PROCEDURE Alters 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, see CREATE PROCEDURE. Syntax ALTER PROC [ EDURE ] procedure_name [ ; number ] [ { @parameter data_type } [ VARYING ] [ = default ] [ OUTPUT ] ] [ ,...n ] [ WITH { RECOMPILE | ENCRYPTION | RECOMPILE , ENCRYPTION } ] [ FOR REPLICATION ] AS sql_statement [ ...n ] Using WAITFOR The 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 WAITFOR statement. 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 SELECT statement: WAITFOR DELAY '00:00:02' SELECT EmployeeID FROM Northwind.dbo.Employees This example uses the TIME keyword to wait until 10 P.M. to perform a check of the pubs specified database to make sure that all pages are correctly allocated and used: USE pubs BEGIN WAITFOR TIME '22:00' DBCC CHECKALLOC END

The disadvantage of the WAITFOR statement is that the connection from the application remains suspended until the WAITFOR completes. WAITFOR is best used when an application or stored procedure must suspend processing for some relatively limited amount of time. Using SQL Server Agent or SQL-DMO to schedule a task is a better method of executing an action at a specific time of day. Comparing CHARINDEX and PATINDEX The 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 can contain wildcard characters. With CHARINDEX, the pattern is a literal string (no wildcard characters). A string-valued expression, usually a column name, in which Microsoft SQL Server searches for the specified pattern. For example, find the position at which the pattern "wonderful" begins in a certain row of the notes column in the titles table. USE pubs SELECT CHARINDEX('wonderful', notes) FROM titles WHERE 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 reports nonzero 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 any row of the Description column in the Categories table: USE Northwind GO SELECT CategoryID, PATINDEX('%candies%', Description)AS POSITION FROM Categories WHERE PATINDEX('%candies%', Description) <> 0 If 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 stored procedures up to 32 levels. The nesting level increases by one when the called stored procedure begins 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 stored procedure chain to fail. The current nesting level for the stored procedures in execution is stored in the @@NESTLEVEL function. Although the nesting limit is 32 levels, Microsoft SQL Server 2000 has no limit on the number of stored procedures that can be invoked from a given stored procedure, provided that the subordinate stored procedures do not invoke other subordinate stored procedures and the maximum 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 RETURN statement to return a return code and check the return code from the calling stored procedure. In this way, you can specify the behavior of your stored procedures when errors occur. For more information about using return codes, see Returning Data Using a Return Code. Nesting Stored Procedures Stored procedures are nested when one stored procedure calls another. You can nest stored procedures up to 32 levels. The nesting level increases by one when the called stored procedure begins 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 stored procedure chain to fail. The current nesting level for the stored procedures in execution is stored in the @@NESTLEVEL function.

Although the nesting limit is 32 levels, Microsoft SQL Server 2000 has no limit on the number of stored procedures that can be invoked from a given stored procedure, provided that the subordinate stored procedures do not invoke other subordinate stored procedures and the maximum 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 RETURN statement to return a return code and check the return code from the calling stored procedure. In this way, you can specify the behavior of your stored procedures when errors occur. For more information about using return codes, see Returning Data Using a Return Code. Stored procedures can even do a nested call to themselves, a technique known as recursion. ISNULL Replaces NULL with the specified replacement value. Syntax ISNULL ( check_expression , replacement_value ) Arguments check_expression Is the expression to be checked for NULL. check_expression can be of any type. replacement_value Is the expression to be returned if check_expression is NULL. replacement_value must have the same type as check_expresssion. Return Types Returns the same type as check_expression. Remarks The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned. Examples A. Use ISNULL with AVG This example finds the average of the prices of all titles, substituting the value $10.00 for all NULL entries in the price column of the titles table. USE pubs GO SELECT AVG(ISNULL(price, $10.00)) FROM titles GO Here is the result set: -------------------------14.24 (1 row(s) affected) SET ANSI_NULL_DFLT_OFF Syntax SET ANSI_NULL_DFLT_OFF {ON | OFF} Remarks This setting only affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements. When SET ANSI_NULL_DFLT_OFF is ON, new columns created with the ALTER TABLE and CREATE TABLE statements are, by default, NOT NULL if the nullability status of the column is not explicitly specified. SET ANSI_NULL_DFLT_OFF has no effect on columns created with an explicit NULL or NOT NULL. Both SET ANSI_NULL_DFLT_OFF and SET ANSI_NULL_DFLT_ON cannot be set ON simultaneously. If one option is set ON, the other option is set OFF. Therefore, either ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON can be set ON, or both can be set OFF. If either option is ON, that setting (SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON) takes effect. If both options are set OFF, Microsoft SQL Server uses the value of the ANSI null default option of sp_dboption. For the most reliable operation of Transact-SQL scripts that may be used in databases with different nullability settings, it is best to always specify NULL or NOT NULL in CREATE TABLE and ALTER TABLE statements. The setting of SET ANSI_NULL_DFLT_OFF is set at execute or run time and not at parse time. RAISERROR

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 a message dynamically with user-specified severity and state information. After the message is defined it is sent back to the client as a server error message. Syntax RAISERROR ( { msg_id | msg_str } { , severity , state } [ , argument [ ,...n ] ] ) [ WITH option [ ,...n ] ] Arguments msg_id Is a user-defined error message stored in the sysmessages table. Error numbers for user-defined error messages should be greater than 50,000. Ad hoc messages raise an error of 50,000. msg_str Is an ad hoc message with formatting similar to the PRINTF format style used in C. The error message can have up to 400 characters. If the message contains more than 400 characters, only the first 397 will be displayed and an ellipsis will be added to indicate that the message has been cut. All ad hoc messages have a standard message ID of 14,000. This format is supported for msg_str: % [[flag] [width] [precision] [{h | l}]] type The parameters that can be used in msg_str are: flag Is 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) Preface the output value with a plus prefix (+) or minus (-) sign if the output value is of signed type. 0 (zero) Zero padding If width is prefaced with 0, zeros are added until the minimum width is reached. When 0 and - appear, 0 is ignored. When 0 is specified with an integer format (i, u, x, X, o, d), 0 is ignored. # 0x prefix for hexadecimal When used with the o, x, or X (number) type of x or X format, the # flag prefaces any nonzero value with 0, 0x, or 0X, respectively. When d, i, or u are prefaced by the # flag, the flag is ignored. ' ' (blank) Space padding Preface the output value with blank spaces if the value is signed and positive. This is ignored when included with the plus sign (+) flag.

DAY 4 & 5
1. Triggers and types of triggers disableing nesting etc 2. Understaning existinf created triggers in Mailcentric 3. Tasks related triggers
4. Functions , All system functions, math, string, datetime, etc.. 3 hrs 4 hrs 1 hr 4 hrs 27/01/2006 27/01/2006 27/01/2006 28/01/2006

5. Creating user defined functions and tasks

4 hrs

28/01/2006

CREATE TRIGGER Creates a trigger, which is a special kind of stored procedure that executes automatically when a user attempts the specified data-modification statement on the specified table. Microsoft SQL Server allows the creation of multiple triggers for any given INSERT, UPDATE, or DELETE statement. Syntax CREATE TRIGGER trigger_name ON { 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 provides declarative referential integrity (DRI) through the table creation statements (ALTER TABLE and CREATE TABLE); however, DRI does not provide cross-database referential integrity. To enforce referential integrity (rules about the relationships between the primary and foreign keys of tables), use primary and foreign key constraints (the PRIMARY KEY and FOREIGN KEY keywords of ALTER TABLE and CREATE TABLE). If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution and prior to the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed (fired).

The first and last AFTER triggers to be executed on a table may be specified by using sp_settriggerorder. Only one first and one last AFTER trigger for each of the INSERT, UPDATE, and DELETE operations may be specified on a table; if there are other AFTER triggers on the same table, they are executed randomly. If an ALTER TRIGGER statement changes a first or last trigger, the first or last attribute set on the modified 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 referential cascade actions and constraint checks associated with the object updated or deleted, has executed successfully. The AFTER trigger sees the effects of the triggering statement as well as all 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 outside the current database. If the trigger owner name is specified (to qualify the trigger), qualify the table name in the same way. The same trigger action can be defined for more than one user action (for example, INSERT and UPDATE) in the same CREATE TRIGGER statement. INSTEAD OF DELETE/UPDATE triggers cannot be defined on a table that has a foreign key with a cascade on DELETE/UPDATE action defined. Any SET statement can be specified inside a trigger. The SET option chosen remains in effect during 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 either SELECT statements that return results, or statements that perform variable assignment in a trigger. A trigger that includes either SELECT statements that return results to the user or statements that perform variable assignment requires special handling; these returned results would have to be written into every application in which modifications to the trigger table are allowed. If variable assignment must occur in a trigger, use a SET NOCOUNT statement at the beginning 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 TABLE statement is, in effect, a DELETE without a WHERE clause (it removes all rows), it is not logged and thus cannot execute a trigger. Because permission for the TRUNCATE TABLE statement defaults 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 DISK RESIZE LOAD LOG CREATE DATABASE DROP DATABASE RECONFIGURE DISK INIT LOAD DATABASE RESTORE DATABASE

RESTORE LOG Note Because SQL Server does not support user-defined triggers on system tables, it is recommended 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 that already 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 each table. Note The default behavior for CREATE TRIGGER (with the compatibility level of 70) is to add additional triggers to existing triggers, if the trigger names differ. If trigger names are the same, SQL Server returns an error message. However, if the compatibility level is equal to or less than 65, any new triggers created with the CREATE TRIGGER statement replace any existing 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 is enabled 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 table T2. 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 UPDATE statement executes each TR1 and TR2 one time. In addition, the execution of TR1 triggers the execution of TR1 (recursively) and TR2. The inserted and deleted tables for a given trigger contain 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 is enabled. There is no defined order in which multiple triggers defined for a given event are executed. Each trigger should be self-contained. Disabling the recursive triggers setting only prevents direct recursions. To disable indirect recursion 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 further triggers are executed.

Nested Triggers Triggers can be nested to a maximum of 32 levels. If a trigger changes a table on which there is another trigger, the second trigger is activated and can then call a third trigger, and so on. If any trigger in the chain sets off an infinite loop, the nesting level is exceeded and the trigger is canceled. To disable nested triggers, set the nested triggers option of sp_configure to 0 (off). The default configuration allows nested triggers. If nested triggers is off, recursive triggers is also disabled, 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 certain distance of one another, or weighted matches. CONTAINS can search for: Syntax CONTAINS ( { column | * } , '< contains_search_condition >' ) 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 the inflectional stem of drives, drove, driving, and driven). A word that has a higher designated weighting than another word.

Das könnte Ihnen auch gefallen