Você está na página 1de 14

Transact SQL

Personal Notes

Table of Contents
SQL Terminology/Acronyms: ................................................................................. 1 SQL Statement Types: .......................................................................................... 2 Order of Operations: ............................................................................................ 2 Data Types OVERVIEW: ........................................................................................ 3 Data Types: ........................................................................................................ 3
- Data Type Precedence .............................................................................................................................................. 6 Example of Datatype in a Date Table..................................................................................................................... 7

Identifier Data Type: ............................................................................................ 6 Uniqueidentifier: .................................................................................................. 8 Timestamp Data Type: ......................................................................................... 8 Sql-variant Data Type:.......................................................................................... 8 Wildcards: .......................................................................................................... 8 Transactions: ...................................................................................................... 9 A Word about NULLS: ........................................................................................... 9 Create Table: ...................................................................................................... 9 Creating Constraints:............................................................................................ 9 Creating Defaults: ...............................................................................................10 Creating Relationships: ........................................................................................10 Basic Select Statement: .......................................................................................11 Select Into Statement: ........................................................................................11 Using JOIN:........................................................................................................12 Table Aliasing:....................................................................................................13 Looking For NULLS: .............................................................................................13 Group By: ..........................................................................................................13 HAVING:............................................................................................................14

SQL Terminology/Acronyms:
Pinning RDBMS Proc PK FK Placing objects (usually tables) in RAM Relational database management system Stored procedure. Primary key Foreign key

Page 1 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes BCP ODBC & OLE DB SARG DBCC GUID BLOB Bulk copy program Database access APIs. Open database connectivity Searchable argument usually comes after the where clause Database consistency checker Globally unique identifier. Binary large object

SQL Statement Types: DCL: Data Control Language. Statements used to change database user permissions or role memberships. Grant Deny Revoke DDL: Data Definition Language. Used to define databases, tables and user defined types.
CREATE ALTER DROP

DML: Data Manipulation Language. Used to manipulate the data in databases.


SELECT INSERT UPDATE DELETE

Variables defined with @ (local) while global @@. Example: DECLARE @LastName char (10) Operators: Arithmetic (+, -, *, /,%) Assignment (=) Bitwise (&, |, ^) used with binary values. & AND, | OR, ^ exclusive OR Comparison (=, >, <, >=, <=, <>, !=, !<, !>) (! MS Extension, not ANSI 92 Standard) Logical (ALL, AND, ANY, BETWEEN, ESISTS, IN, LIKE, NOT, OR, SOME) String Concatenation (+) Unary (+ positive, - negative)

Order of Operations:
1. + (Positive), - (Negative), (Bitwise Exclusive NOT) 2. * (Multiply), / (Divide), % (Modulo) Page 2 of 14
2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes 3. 4. 5. 6. 7. 8. 9. + (Add), + (Concatenate), - (Subtract) =, >, <, >=, <=, <>, !=, !<, !> (Comparison) ^ (Bitwise Exclusive OR), & (Bitwise AND), | (Bitwise OR) NOT AND ALL, ANY, BETWEEN, IN, LIKE, OR, SOME = (Assignment)

Data Types OVERVIEW:


The following objects have data types: Columns in tables and views Parameters in stored procedures Variables Transact-SQL functions that return one or more data values of a specific data type Stored procedures that have a return code, which always has an integer data type.

Data Types:
1. 2. 3. 4. 5. Exact Numeric Approximate Numeric Character String (non-Unicode) Binary String Unicode

1. Exact Numeric: Exact number data types that uses integer data. o bigint Integer (whole number) data from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807) Store size is 8 bytes. o int Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31-1 (2,147,483,647) Store size is 4 bytes. o smallint Integer data from -2^15 (-32,768) through 2^15-1 (32,767) Store size is 2 bytes. o tinyint

Page 3 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Integer data from 0 through 255 Storage size is 1 byte o bit Integer data type 1, 0, or NULL 1 bit of storage o decimal and numeric decimal: fixed precision and scale numeric data from 10^38 +1 through 10^38 -1 (1 with 39 0s +1) 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. Scale: specifies the maximum number of decimal digits that can be stored to the right of the decimal point. numeric: functionally equivalent to decimal

o Monetary data types for representing monetary or currency values. Money 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 thousands of a monetary unit. Storage size is 8 bytes. smallmoney Monetary data values from -214,748.3648 though 214,748.3647, with accuracy to ten thousands of a monetary unit. Storage size is 4 bytes.

2. Approximate Numeric:
Approximate number data types for use with floating points numeric data; not all values in the data type range can be precisely represented. Float: floating point number data from - 1.79E + 308 through 1.79E + 308. storage size is 8 bytes. Real: floating point number data from - 3.40E + 38 through 3.40E + 38. Storage size is 4 bytes. Date and Time data types for representing date and time of day.

Page 4 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes datetime: date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second. smalldatetime: date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute.

3. Character String (Non-Unicode):


Fixed-length (char) on 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. 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. Text: variable-length non-Unicode data in the code page of the server and with a maximum length of 2 31 -1 (2, 147, 483, 647) characters. 4. Binary String: Binary data types of either fixed-length (binary) or variable-length (varbinary). If you storing binary data (pictures/bitmaps) binary [(n)]: Fixed-length binary data of n bytes. n must be a value from 1 through 8000. Storage size is n+4 bytes. varbinary [(n)]: variable-length binary data of n bytes. n must be a value from 1 through 8000. Storage size is the actual length of the data entered +4 bytes, not n bytes. image: variable-length binary data from 0 through 2 31 -1 (2, 147, 483, 647) bytes.

5. Unicode
nchar (n): fixed-length Unicode character data of n characters. n must be a value from 1 through 4,000 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.

Page 5 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes ntext: variable-length Unicode data with a maximum length of 2 30 -1 (1, 073, 741, 823) characters.

- Data Type Precedence

When two expressions of different data types are combined by an operator, the data type precedence rules specify which data type is converted to the other. The data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned. When both operand expressions have the same data type, the result of the operation has that data type. This is the precedence order for the Microsoft SQL Server 2000 data types: sql_variant (highest) datetime smalldatetime float real decimal money smallmoney bigint int smallint tinyint bit ntext text image timestamp uniqueidentifier nvarchar nchar varchar char varbinary binary (lowest)

Identifier Data Type:


Not really a separate data type. Its a property. Assign numbers automatically to specific fields. Can be set for: tinyint, smallint, int, bigint, decimal or numeric. Configure seed (starting number) and increment value.

Page 6 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes

Example of Datatype in a Date Table

These are some possible attribute columns that may be used in a date table. Fiscal year versions are the same, although values such as quarter numbers may differ. Column name date_key day_date day_of_week week_begin_date week_num month_num month_name Data type int smalldatetime char smalldatetime tinyint tinyint char 1 to 52 or 53 1 to 12 January Jan Useful for days in the month Alternative for, or in addition to month_end_date yyyymm 1 to 4 1Q2000 Week 1 defined by business rules Monday Format/Example Comment yyyymmdd

month_short_name char month_end_date days_in_month yearmo quarter_num quarter_name year weekend_ind workday_ind weekend_weekday smalldatetime tinyint int tinyint char smallint bit bit char

Indicates weekend Indicates work day weekend Alternative for weekend_ind and weekday_ind. Can be used to make reports more readable. Indicates holiday Thanksgiving

holiday_ind holiday_name

bit char

Page 7 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Column name peak_period_ind Data type bit Format/Example Comment Meaning defined by business rules

Uniqueidentifier:
Uses a 15 byte GUID (globally unique id generated by sql server) Example: {40700425-0080-11d2851f-00c04fc21759} Used by SQL Server for replication Generate values automatically by using the NEWID() function as the default value

Timestamp Data Type:


These are values (numbers) created automatically by SQL Server anytime the data in a row changes. It allows you to keep track of the data changes in a row, also called rowversion. Nothing to do with date or time. An 8-byte binary value. Can be used in replicated databases in SQL Server 2000 You can compare to timestamp data to see which one is greater, it helps knowing the changes that happened to a row.

Sql-variant Data Type:


New in SQL Server 2000 Can hold any other type of value except text, ntext, image, and timestamp.

Wildcards:
Wildcards available in search conditions: % any string of zero or more characters. o Ex: LIKE Mc% Returns all strings beginning with Mc (such as _ (underline) any single character [] any single character within the specific range [^] any single character not within the specified range.

Page 8 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes

Transactions:
SQL Server Operates in three transaction modes: Autocommit Transactions: Each individual statement is a transaction. Explicit Transactions: Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement. Implicit Transactions: A new transaction is implicitly started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or ROLLBACK statement.

A Word about NULLS: Two nulls are not equal SET ANSI_NULLS
Changes how NULLS are evaluated by queries Set ANSI_NULLS ON will not recognize NULL values using the equal (=) sign. Set ANSI_NULLS OFF will recognize NULL values using the equal (=) sign.

Create Table: Syntax: CREATE TABLE <name>


(column_name datatype column_name2 datatype NULL/NOT NULL, NULL/NOT NULL)

Creating Constraints:
Constraints tell SQL Server how to automatically enforce data integrity Constraints define rules regarding the values allowed in columns Most efficient integrity tool Constraints can be done in two ways: Page 9 of 14
2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Table creation (CREATE TABLE) After table has been created (ALTER TABLE) Example (inside the create table statement): Create table testconstraint (name varchar(20) not null, age char(2) not null check (age>18)) Example (After table has been created): Create table testconstraint (name varchar(20) not null, age char(2) not null) alter table testconstraint add constraint checkage check (age>18) SQL Server 2000 supports five classes of constraints: 1. 2. 3. 4. NOT NULL specifies that the column does not accept NULL values. CHECK constraints limit the values that can be input into a column UNIQUE constraints enforce the uniqueness of the values in a set of columns PRIMARY KEY constraints identify the column or set of columns whose values uniquely identify a row in a table 5. FOREIGN KEY constraints identify the relationships between tables

Creating Defaults:
Defaults can be: Constant Built-in function Mathematical expression Example: Create table testconstraint (name varchar(20) not null, age char(2) not null, state char(2) not null default TN)

Creating Relationships:

Page 10 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Example: alter table address add constraint fk_address foreign key (id) references customers (id)

Basic Select Statement:


Check out the syntax and the clauses you can use it with from books online.

Select Into Statement:


SELECT select_list [Into new_table] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY order_expression [ASC | DESC] ] Creates a new table and inserts the resulting rows from the query into it. Example: Select fname, lname, phone Into testable From authors Create an identical table definition (different name) with no data by having a FALSE condition in the WHERE clause.

Example: Select fname, lname, phone Into testable From authors Where fname = jjjj

Page 11 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes

Using JOIN:
Retrieve data from two or more tables based on logical relationships between tables. A join condition defines the way two tables area related in a query by: o Specifying the column from each table to be used for the join. o Specifying a logical operator (=, <>, and so on) to be used in comparing values from the columns. There are three kinds of joins: Inner Join: inner joins use a comparison operator to match rows from two tables on the values in common column from each table. Only return data if those two column match. Outer Join: Left Outer: the result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. Right Outer: all rows from the right are returned. Full: full outer join returns all rows in both the left and the right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. Cross Join: cross joins return all rows from the left table, each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products.

Example: (inner join) Use pubs Select stores.stor_name, stores.city, sales.qty, sales.ord_date From stores Join sales On stores.stor_id = sales.stor_id Where sales.qty > 25 Example: (left outer join) Use pubs Select stores.stor_name, stores.city, sales.qty, sales.ord_date From stores Left outer Join sales On stores.stor_id = sales.stor_id

Page 12 of 14

2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Example: (cross join) Use pubs Select stores.stor_name, sales.qty From stores Cross Join sales Read more.

Table Aliasing:
Used to provide easier reading of T-SQL query Can be assigned with or without AS keyword All references to the table in the T-SQL statement must use the alias, not the table name.

Example: (table aliasing) Use pubs Select s.stor_name, s.city, sl.qty From stores as s Join sales as sl On s.stor_id = sl.stor_id

Looking For NULLS:


NULL means UNKOWN NULL does not mean empty or zero NULL does not equal NULL NULL IS (meaning the data is unknown) NULL IS NOT (meaning that data is known)

Example: Use northwind Select contactname, region From customers Where region IS NULL If you write Where region = NULL you will get nothing because null is unknown value.

Group By:
Used after the WHERE clause to group result set rows. If an aggregate function is used in the select clause, a summary value is calculated for each group. EVERY column in the SELECT list, except for the aggregated columns, must be specified in the GROUP BY list. Page 13 of 14
2005

Created by Ahmed M. Elsadek

Transact SQL
Personal Notes Example: Use pubs Select stor_id, sum(qty) as total sales by store From sales Where qty>10 Group by stor_id

HAVING:
Example: Use pubs Select stor_id, sum(qty) as total sales by store From sales Group by stor_id Having sum(qty)>60

Page 14 of 14

2005

Created by Ahmed M. Elsadek

Você também pode gostar