sq l server final soft copy
TRANSCRIPT
-
8/13/2019 Sq l Server Final Soft Copy
1/183
System Databases in SQL Server
System databases are an integral part of the SQL Server product as it depends on the System
Databases to function. Having a good knowledge of System Databases will help the Database
Administrator to perform day-to-day tasks effectively.
System Database in SQL Server 2005 & 2008 Versions
Master DatabaseThe Master database basically consists of two physical files, namely master.mdf (data file) and
mastlog.ldf (log file). By default when you are installing SQL Server 2008 the master database
related data and log file are installed in the following folder location Drive:\Program
Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\. If master database iscorrupted or if it is not available then the SQL Server Service will not start.
Model Database
The Model database basically consists of two physical files namely Model.mdf (data file) and
ModelLog.ldf (log file).Physical Path---- Drive:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\. If the Model database is damaged or
corrupted then SQL Server Service will not start up as it will not be able to create the tempdb
database.
MSDB Database
The MSDB database basically consists of two physical files namely MSDBData.mdf (data file)
and MSDBLog.ldf (log file). By default when you are installing SQL Server 2008 the MSDB
database related data and log file are created in the following folder location Drive:\ProgramFiles\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\. If the MSDB
database is corrupted or damaged then scheduling information used by SQL Server Agent will be
lost.
TempDB Database
The TempDB database basically consists of two physical files namely tempdb.mdf (data file)and templog.ldf (log file). By default when you are installing SQL Server 2008 the TempDBdatabase related data and log file are created in the following folder location Drive:\Program
Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\.
Resource Database The physical file names of Resource database is mssqlsystemresource.mdf and
mssqlsystemresource.ldf.
-
8/13/2019 Sq l Server Final Soft Copy
2/183
Drive:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Binn
ReportServer The ReportServer database is created when a user installs SQL Server Reporting Service. Thisdatabase basically stores all the metadata and object related information which is used by
reporting services.
The ReportServer database basically consists of two physical files namely ReportServer.mdf(data file) and ReportServer_log.ldf (log file). By default when you are installing SQL Server2008 Reporting Services the ReportServer database related data and log file are created in the
following folder location Drive:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\.
ReportServerTempDB The ReportServerTempDB database basically consists of two physical files namely
ReportServerTempDB.mdf (data file) and ReportServerTempDB_log.ldf (log file). By defaultwhen you are installing SQL Server 2008 Reporting Services the ReportServer database related
data and log file are created in the following folder location Drive:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\.DistributionThe distribution database basically consists of two physical files namely distribution.mdf (data
file) and distribution_log.ldf (log file). By default when you are configuring replication the
distribution database related data and log file are created in the following folder locationDrive:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\.
Create Database Command:
Creates a new database and the files used to store the database, or attaches a database from the
files of a previously created database.
A maximum of 32,767 databases can be specified on a server.
There are three types of files used to store a database:
The primary file contains the startup information for the database. The primary file is also
used to store data. Every database has one primary file.
Secondary files hold all of the data that does not fit in the primary data file. Databases
need not have any secondary data files if the primary file is large enough to hold all of the
data in the database. Other databases may be large enough to need multiple secondarydata files, or they may use secondary files on separate disk drives to spread the data
across multiple disks.
Transaction log files hold the log information used to recover the database. There must be
-
8/13/2019 Sq l Server Final Soft Copy
3/183
at least one transaction log file for each database, although there may be more than one.
The minimum size for a transaction log file is 512 KB.
Every database has at least two files, a primary file and a transaction log file.
File type File name extensionPrimary data file .mdf
Secondary data file .ndf
Transaction log file .ldf
Note The master database should be backed up when a user database is created.
Fractions cannot be specified in the SIZE, MAXSIZE, and FILEGROWTH parameters. To
specify a fraction of a megabyte in SIZE parameters, convert to kilobytes by multiplying the
number by 1,024. For example, specify 1,536 KB instead of 1.5 MB (1.5 multiplied by 1,024
equals 1,536).
When a simple CREATE DATABASE database_name statement is specified with no additional
parameters, the database is made the same size as the model database.
A. Create a database that specifies the data and transaction log files
This example creates a database called Sales. Because the keyword PRIMARY is not used, the
first file (Sales_dat) becomes the primary file. Because neither MB or KB is specified in theSIZE parameter for the Sales_dat file, it defaults to MB and is allocated in megabytes. The
Sales_log file is allocated in megabytes because the MB suffix is explicitly stated in the SIZE
parameter.
USE master GO CREATE DATABASE Sales ON( NAME = Sales_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5 )
LOG ON ( NAME = 'Sales_log',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf',SIZE = 5MB,MAXSIZE = 25MB,FILEGROWTH = 5MB )
GO
B. Create a database specifying multiple data and transaction log files
This example creates a database called Archive with three 100-MB data files and two 100-MB
transaction log files. The primary file is the first file in the list and is explicitly specified with the
-
8/13/2019 Sq l Server Final Soft Copy
4/183
PRIMARY keyword. The transaction log files are specified following the LOG ON keywords.
Note the extensions used for the files in the FILENAME option: .mdf is used for primary data
files, .ndf is used for the secondary data files, and .ldf is used for transaction log files.
USE master GO
CREATE DATABASE ArchiveON PRIMARY ( NAME = Arch1,
FILENAME = 'c:\program files\microsoft sqlserver\mssql\data\archdat1.mdf',
SIZE = 100MB,MAXSIZE = 200,FILEGROWTH = 20),
( NAME = Arch2, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat2.ndf',SIZE = 100MB,MAXSIZE = 200,FILEGROWTH = 20),
( NAME = Arch3, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat3.ndf',SIZE = 100MB,MAXSIZE = 200,FILEGROWTH = 20)
LOG ON( NAME = Archlog1,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\archlog1.ldf',SIZE = 100MB,MAXSIZE = 200,FILEGROWTH = 20),
( NAME = Archlog2,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\archlog2.ldf',SIZE = 100MB,MAXSIZE = 200,FILEGROWTH = 20)
GO
C. Create a simple database
This example creates a database called Products and specifies a single file. The file specified becomes the primary file, and a 1-MB transaction log file is automatically created. Because
neither MB or KB is specified in the SIZE parameter for the primary file, the primary file is
allocated in megabytes. Because there is no for the transaction log file, the transaction
log file has no MAXSIZE and can grow to fill all available disk space.
-
8/13/2019 Sq l Server Final Soft Copy
5/183
-
8/13/2019 Sq l Server Final Soft Copy
6/183
then all the pages for the object are allocated from the specified filegroup.
F. Create a database with filegroups
This example creates a database named sales with three filegroups:
The primary filegroup with the files Spri1_dat and Spri2_dat. The FILEGROWTH
increments for these files is specified as 15 percent.
A filegroup named SalesGroup1 with the files SGrp1Fi1 and SGrp1Fi2.
A filegroup named SalesGroup2 with the files SGrp2Fi1 and SGrp2Fi2.
CREATE DATABASE Sales ON PRIMARY ( NAME = SPri1_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\SPri1dat.mdf',SIZE = 10,
MAXSIZE = 50,FILEGROWTH = 15% ),
( NAME = SPri2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\SPri2dt.ndf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 15% ),
FILEGROUP SalesGroup1 ( NAME = SGrp1Fi1_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\SG1Fi1dt.ndf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5 ),
( NAME = SGrp1Fi2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\SG1Fi2dt.ndf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5 ),
FILEGROUP SalesGroup2 ( NAME = SGrp2Fi1_dat,
FILENAME = 'c:\program files\microsoft sql server\mssql\data\SG2Fi1dt.ndf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5 ),
( NAME = SGrp2Fi2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\SG2Fi2dt.ndf',SIZE = 10,MAXSIZE = 50,FILEGROWTH = 5 )
LOG ON ( NAME = 'Sales_log',
FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf',SIZE = 5MB,MAXSIZE = 25MB,FILEGROWTH = 5MB )
-
8/13/2019 Sq l Server Final Soft Copy
7/183
GO
SQL Server Datatypes
Data types in SQL Server are organized into the following categories:
Exact numerics Unicode character strings
Approximate numerics Binary strings
Date and time Other data types
Character strings
In SQL Server, based on their storage characteristics, some data types aredesignated as belonging to the following groups:
• Large value data types: varchar(max), nvarchar(max), and varbinary(max)• Large object data types: text, ntext, image, varchar(max), nvarchar(max),
varbinary(max), and xml
Exact Numerics
Integers
bigint
Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808) through
2^63-1 (9,223,372,036,854,775,807).
int
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1(2,147,483,647).
smallint
Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767).
tinyint
Integer data from 0 through 255.
http://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933198(v=sql.80).aspx
-
8/13/2019 Sq l Server Final Soft Copy
8/183
bit
Integer data with either a 1 or 0 value.
decimal
Fixed precision and scale numeric data from -10^38 +1 through 10^38 – 1.
numeric
Functionally equivalent to decimal.
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-thousandth of a monetaryunit.
smallmoney
Monetary data values from -214,748.3648 through +214,748.3647, with accuracy
to a ten-thousandth of a monetary unit.
Approximate Numerics
float
Floating precision number data with the following valid values: -1.79E + 308
through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308.
real
Floating precision number data with the following valid values: -3.40E + 38through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38.
datetime and smalldatetime
datetime
Date and time data from January 1, 1753, through December 31, 9999, with anaccuracy of three-hundredths of a second, or 3.33 milliseconds.
smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with an accuracy
http://msdn.microsoft.com/en-us/library/aa225961(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225961(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258277(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258876(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258832(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225961(v=sql.80).aspx
-
8/13/2019 Sq l Server Final Soft Copy
9/183
of one minute.
Character Strings
char
Fixed-length non-Unicode character data with a maximum length of 8,000characters.
varchar
Variable-length non-Unicode data with a maximum of 8,000 characters.
text
Variable-length non-Unicode data with a maximum length of 2^31 - 1(2,147,483,647) characters.
Unicode Character Strings
nchar
Fixed-length Unicode data with a maximum length of 4,000 characters.
nvarchar
Variable-length Unicode data with a maximum length of 4,000 characters.
sysname is a system-supplied user-defined data type that is functionally equivalent
to nvarchar(128) and is used to reference database object names.
ntext
Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823)
characters.
Binary Strings
binary
Fixed-length binary data with a maximum length of 8,000 bytes.
varbinary
Variable-length binary data with a maximum length of 8,000 bytes.
image
Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.
Other Data Types
cursor
http://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260619(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260619(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276838(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276838(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933226(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933226(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258247(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258247(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258247(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933226(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa225972(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276838(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa276823(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260619(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258242(v=sql.80).aspx
-
8/13/2019 Sq l Server Final Soft Copy
10/183
A reference to a cursor.
sql_variant
A data type that stores values of various SQL Server-supported data types, excepttext, ntext, timestamp, and sql_variant.
table
A special data type used to store a result set for later processing .
timestamp
A database-wide unique number that gets updated every time a row gets updated.
uniqueidentifier
A globally unique identifier (GUID).
Data type precedences:
When an operator combines two expressions of different data types, the rules fordata type precedence specify that the data type with the lower precedence is
converted to the data type with the higher precedence. If the conversion is not asupported implicit conversion, an error is returned. When both operand expressions
have the same data type, the result of the operation has that data type.
SQL Server uses the following precedence order for data types:
1. user-defined data types (highest)
2. sql_variant
3. xml
4. datetimeoffset
5. datetime2
6. datetime
7. smalldatetime
8. date
9. time
10. float
11. real
12. decimal
13. money
14. smallmoney
http://msdn.microsoft.com/en-us/library/aa259247(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa259247(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260638(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260638(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260631(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260631(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260656(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260656(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260656(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260631(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260638(v=sql.80).aspxhttp://msdn.microsoft.com/en-us/library/aa259247(v=sql.80).aspx
-
8/13/2019 Sq l Server Final Soft Copy
11/183
15. bigint
16. int
17. smallint
18. tinyint
19. bit
20. ntext
21. text
22. image
23. timestamp
24. uniqueidentifier
25. nvarchar (including nvarchar(max) )
26. nchar
27. varchar (including varchar(max) )
28. char
29. varbinary (including varbinary(max) )
30. binary (lowest)
Type Storage in bytes
bigint 8
Int 4
Smallint 2
Tinyint 1
Bit 1 bit
Decimal and numeric precision 1-9 5
Decimal and numeric precision 10-19 9
Decimal and numeric precision 20-28 13
Decimal and numeric precision 29-38 17
Money 8
-
8/13/2019 Sq l Server Final Soft Copy
12/183
Smallmoney 4
Float 7 digit precision 4
Float 15 digit precision 8
Real 4
Datetime Two 4 byte integersSmalldatetime Two 2 byte integers
Char (ASCII coding system),varchar Each char occupies 1 byte
Nchar(UNICODE system),nvarchar Each nchar occupies 2 bytes
Create Table Command:
Syntax:
CREATE TABLE table_name (col1-name data-type(width if any)
CONSTRAINT constraint-name , col2-name data-type(width if any)
CONSTRAINT constraint-name …..........)
-
8/13/2019 Sq l Server Final Soft Copy
13/183
CREATE TABLE Customer ( CustomerId int PRIMARY KEY, FName nvarchar (30), LName nvarchar (30),
Phone char (13) UNIQUE, Street nvarchar (30), City nvarchar (20) NOT NULL, ZipCode char (10) NOT NULL)
GO
Inserting Records into a Table:
Syntax:
INSERT INTO table-name (col1,col2,col3,...)VALUES(val1,val2,val3,......) insert into Customer values (200112,'Jake','Kline','(814)237-6871','2352 8th Avenue','LA','16444-0256'), (200334,'Abigail','Brown','(814)237-2310','124 North Land','LA','16444-0312'), (200123,'Reginald','Smyth',null,'P.O.Box 200','NY','15432-0021'), (210222,'Steve','Haag','(410)416-7799','1372 Ivanhoe','Chicago','22100-2555')
go
Create Table Rental (CustomerId int references Customer , VideoNumber char (6) references Video(VideoNum), DateRented datetime not null, DateReturned datetime) go
Insert into Rental values( 200334,'4371-1','09/22/06',null)
go
Create Table Video
-
8/13/2019 Sq l Server Final Soft Copy
14/183
(VideoNum char (6) primary key, VTitle nvarchar (30) not null, VType nvarchar (20) not null, DistNum int references Distributor (DistributorNum),
Price decimal(5,2) not null check (Price between 1 and 5) )
go
insert into Video values ('1111-1','Gone with the breeze','Drama',986,3), ('1111-2','Gone with the breeze','Drama',986,3),
('2351-6','Attack of killer tomatoes','Horror',381,1.5), ('4371-1','Alien Surfer','Sci-Fi',457,2), ('4780-1','Three Stooges in Las Vegas','Comedy',235,2),
('4777-1','Gods Must be crazy','Comedy',235,5)
go
Create Table Distributor (DistributorNum int primary key, DistributorName nvarchar (30) not null, Phone char (13) not null) go
insert into Distributor values
(235,'Disney Studios','(800)243-0000'), (986,'Universal Studios','(800)565-0000'), (457,'Paramount Pictures','(800)322-5555'), (381,'Tri-Star Productions','(800)665-8998') go
-
8/13/2019 Sq l Server Final Soft Copy
15/183
INTEGRITY CONSTRAINTS
Nullability Rules Within a Table Definition
The nullability of a column determines whether or not that column can allow a null value(NULL) as the data in that column. NULL is not zero or blank: it means no entry was made or an
explicit NULL was supplied, and it usually implies that the value is either unknown or notapplicable.
PRIMARY KEY Constraints
A table can contain only one PRIMARY KEY constraint.
The index generated by a PRIMARY KEY constraint cannot cause the number of indexes
on the table to exceed 249 nonclustered indexes and 1 clustered index.
If CLUSTERED or NONCLUSTERED is not specified for a PRIMARY KEY constraint,
CLUSTERED is used if there are no clustered indexes specified for UNIQUE constraints.
All columns defined within a PRIMARY KEY constraint must be defined as NOT
NULL. If nullability is not specified, all columns participating in a PRIMARY KEY
constraint have their nullability set to NOT NULL.
UNIQUE Constraints
If CLUSTERED or NONCLUSTERED is not specified for a UNIQUE constraint,
NONCLUSTERED is used by default.
Each UNIQUE constraint generates an index. The number of UNIQUE constraints cannot
cause the number of indexes on the table to exceed 249 nonclustered indexes and 1
clustered index.
FOREIGN KEY Constraints
When a value other than NULL is entered into the column of a FOREIGN KEY
constraint, the value must exist in the referenced column; otherwise, a foreign key
violation error message is returned.
FOREIGN KEY constraints are applied to the preceding column unless source columns
are specified.
FOREIGN KEY constraints can reference only tables within the same database on the
same server. Cross-database referential integrity must be implemented through triggers.
FOREIGN KEY constraints can reference another column in the same table (a
self-reference).
The REFERENCES clause of a column-level FOREIGN KEY constraint can list only one
-
8/13/2019 Sq l Server Final Soft Copy
16/183
reference column, which must have the same data type as the column on which the
constraint is defined.
The REFERENCES clause of a table-level FOREIGN KEY constraint must have the
same number of reference columns as the number of columns in the constraint column
list. The data type of each reference column must also be the same as the corresponding
column in the column list.
A table can contain a maximum of 253 FOREIGN KEY constraints.
FOREIGN KEY constraints are not enforced on temporary tables.
A table can reference a maximum of 253 different tables in its FOREIGN KEY
constraints.
FOREIGN KEY constraints can reference only columns in PRIMARY KEY or UNIQUE
constraints in the referenced table or in a UNIQUE INDEX on the referenced table.
use videorentalsystem
go
CREATE TABLE Dept( deptno int primary key,
dname nvarchar (20) not null, loc nvarchar (20) not null) go
CREATE TABLE Emp(
empid int primary key, ename nvarchar (20) not null,
job nvarchar (20) not null,
salary int not null, deptno int references Dept(deptno)) go
-------------------------------------*
CREATE TABLE Emp2(
empid int primary key,
-
8/13/2019 Sq l Server Final Soft Copy
17/183
ename nvarchar (20) not null, job nvarchar (20) not null, salary int not null, deptno int,
foreign key(deptno)references Dept(deptno)) go
-------------------------------------*
Create table TX
(col1x int, col2x int,
col3x nvarchar (10), primary key(col1x,col2x)) go
Create table TY (col1y int, col2y int,
col3y int,
Constraint TY_fk Foreign Key (col1y,col2y) references TX(col1x,col2x)) go
-------------------------------------*
Create table AA(
col1 int primary key,
col2 nvarchar (10), col3 int unique) go
Create table BB( col1 nvarchar (20), col2 int references AA)
-
8/13/2019 Sq l Server Final Soft Copy
18/183
go
----------------------------------------*
Create table CC(
col1 nvarchar (20),
col2 int references AA(col3)) go
------------------*
DEFAULT Definitions
A column can have only one DEFAULT definition.
A DEFAULT definition can contain constant values, functions, SQL-92 niladic functions,
or NULL. The table shows the niladic functions and the values they return for the default
during an INSERT statement.
SQL-92 niladic function Value returned
CURRENT_TIMESTAMP Current date and time.
CURRENT_USER Name of user performing insert.
SESSION_USER Name of user performing insert.SYSTEM_USER Name of user performing insert.
USER Name of user performing insert.
constant_expression in a DEFAULT definition cannot refer to another column in the
table, or to other tables, views, or stored procedures.
DEFAULT definitions cannot be created on columns with a timestamp data type or
columns with an IDENTITY property.
DEFAULT definitions cannot be created for columns with user-defined data types if the
user-defined data type is bound to a default object.
-
8/13/2019 Sq l Server Final Soft Copy
19/183
Defaults supply a value (with the INSERT and UPDATE statements) when no
value is supplied. For example, the AdventureWorks2008R2 database couldinclude a lookup table listing the different jobs employees can fill in the company.
Under a column that describes each job, a character string default could supply a
description when an actual description is not entered explicitly.
DEFAULT 'New Position - title not formalized yet'
In addition to constants, DEFAULT definitions can include functions. Use the following
example to get the current date for an entry.
DEFAULT (getdate())
A niladic-function scan can also improve data integrity. To keep track of the user that inserted a
row, use the niladic-function for USER. Do not enclose the niladic-functions with parentheses.
DEFAULT USER
CHECK Constraints
A column can have any number of CHECK constraints, and the condition can includemultiple logical expressions combined with AND and OR. Multiple CHECK constraints
for a column are validated in the order created.
The search condition must evaluate to a Boolean expression and cannot reference another
table.
A column-level CHECK constraint can reference only the constrained column, and a
table-level CHECK constraint can reference only columns in the same table.
CHECK CONSTRAINTS and rules serve the same function of validating the data during
INSERT and DELETE statements.
When a rule and one or more CHECK constraints exist for a column or columns, allrestrictions are evaluated.
use videorentalsystem go
create table T7(
-
8/13/2019 Sq l Server Final Soft Copy
20/183
col1 int primary key , col2 nvarchar (10), col3 int check (col3 >= 10 And col3 = 10 And col3
-
8/13/2019 Sq l Server Final Soft Copy
21/183
Composite Primary Key:
CREATE TABLE Emp_Hrs(
EmpId int, DeptNo int,
HrsWkd int, PRIMARY KEY(EmpId,DeptNo)) GO
DROP TABLE Emp_Hrs GO
Difference between Clustered and Non-Clustered Indexes:
I am explaining you with an example, The TelephoneDirectory is a fine example of Clustered Index as data andindex are at the same page, whereas index in the back sideof the book is a fine example of non-clustered index andnon-clustered index is a fast B-tree structure as indexjust points to the data page. Also only one clustered indexis possible per table and 249 non-clustered index per table.
Clustered index is unique for anygiven table and we can have only one clustered index on atable. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db.
-
8/13/2019 Sq l Server Final Soft Copy
22/183
Using Clustered Indexes
PRIMARY KEY constraint creates clustered index
automatically, if no clustered index already exists on the
table and a nonclustered index is not specified while
imposing the PRIMARY KEY constraint.
Before creating clustered indexes, understand how your data will be accessed.Consider using a clustered index for:
Columns that contain a large number of distinct values.
Queries that return a range of values using operators such as BETWEEN, >, >=,
-
8/13/2019 Sq l Server Final Soft Copy
23/183
use videorentalsystem go
create table T1( col1 int primary key clustered,
col2 nvarchar (10), col3 int unique) go
------------------------------------------*
use videorentalsystem go
create table T2(
col1 int primary key clustered, col2 nvarchar (10), col3 int unique clustered) go
Msg 8112, Level 16, State 0, Line 2
Cannot add more than one clustered index for constraints on table 'T2'.
------------------------------------------------*
use videorentalsystem go
create table T3( col1 int primary key , col2 nvarchar (10),
col3 int unique clustered)
go
--------------------------------------------*
use videorentalsystem go
-
8/13/2019 Sq l Server Final Soft Copy
24/183
create table T4( col1 int , col2 nvarchar (10), col3 int unique ,
primary key clustered(col1,col2) ) go
-------------------------------------------*
use videorentalsystem go
create table T5(
col1 int primary key,
col2 nvarchar (10), col3 int , unique clustered(col2,col3) )
go
--------------------------------------------*
use videorentalsystem
go
create table T6(
col1 int primary key nonclustered, col2 nvarchar (10), col3 int ,
)
go
---------------------------------------*
CREATE TABLE Stars (StarID int PRIMARY KEY NONCLUSTERED,
StarName varchar (50) Unique, SolarMass decimal(10,2) CHECK (SolarMass > 0),
StarType varchar (50) DEFAULT 'Orange Giant');
GOCREATE CLUSTERED INDEX Ix_Star_Name ON Stars(StarName)
-
8/13/2019 Sq l Server Final Soft Copy
25/183
GO
CREATE NONCLUSTERED INDEX Ix_Star_Type ON Stars (StarType)
GO-----------------------------------------------------------------*
ALTER TABLE Command:
A. Adding a new column
The following example adds a column that allows null values and has no values provided
through a DEFAULT definition. In the new column, each row will have NULL.
use videorentalsystemgo
CREATE TABLE doc_exa (column_a INT) ;
GO
ALTER TABLE doc_exa ADD column_b VARCHAR (20) NULL ; GO
EXEC sp_help doc_exa ; GO
DROP TABLE doc_exa ;
GO
B. Dropping a column
The following example modifies a table to remove a column.
-
8/13/2019 Sq l Server Final Soft Copy
26/183
use videorentalsystemgo
CREATE TABLE doc_exb (column_a INT, column_b VARCHAR (20) NULL) ;
GOALTER TABLE doc_exb DROP COLUMN column_b ; GOEXEC sp_help doc_exb ; GODROP TABLE doc_exb ; GO
C. Changing the data type of a column
The following example changes a column of a table from INT to DECIMAL.
use videorentalsystem
go
CREATE TABLE doc_exy (column_a INT ) ; GO
INSERT INTO doc_exy (column_a) VALUES (10) ; GO
Select * from doc_exy go
exec sp_help doc_exy go
ALTER TABLE doc_exy ALTER COLUMN column_a DECIMAL (5, 2) ; GODROP TABLE doc_exy ; GO
-
8/13/2019 Sq l Server Final Soft Copy
27/183
D. Adding a column with a constraint
The following example adds a new column with a UNIQUE constraint.
Use VideoRentalSystem
go
CREATE TABLE doc_exc (column_a INT) ; GO
ALTER TABLE doc_exc ADD column_b VARCHAR (20) NULL CONSTRAINT exb_unique UNIQUE ;
GO
EXEC sp_help doc_exc ; GO
DROP TABLE doc_exc ;
GO
E. Adding an unverified CHECK constraint to an existing column
The following example adds a constraint to an existing column in the table. The column has a
value that violates the constraint. Therefore, WITH NOCHECK is used to prevent the constraint
from being validated against existing rows, and to allow for the constraint to be added.
Use VideoRentalSystemgo
CREATE TABLE doc_exd ( column_a INT) ;
GOINSERT INTO doc_exd VALUES (-1) ;
GO
ALTER TABLE doc_exd WITH NOCHECK
ADD CONSTRAINT exd_check CHECK (column_a > 1) ; GO
Select * from doc_exdgo
EXEC sp_help doc_exd ;
GODROP TABLE doc_exd ; GO
-
8/13/2019 Sq l Server Final Soft Copy
28/183
F. Adding a DEFAULT constraint to an existing column
The following example creates a table with two columns and inserts a value into the first column,
and the other column remains NULL. A DEFAULT constraint is then added to the secondcolumn. To verify that the default is applied, another value is inserted into the first column, andthe table is queried.
CREATE TABLE doc_exz ( column_a INT, column_b INT) ;
GO
INSERT INTO doc_exz (column_a)VALUES ( 7 ) ; GO
ALTER TABLE doc_exz ADD CONSTRAINT col_b_def DEFAULT 50 FOR column_b ;
GO
INSERT INTO doc_exz (column_a) VALUES ( 10 ) ; GO
SELECT * FROM doc_exz ; GO
DROP TABLE doc_exz ;
GO
G. Adding several columns with constraints
The following example adds several columns with constraints defined with the new column. Thefirst new column has an IDENTITY property. Each row in the table has new incremental values
in the identity column.
Use VideoRentalSystem
go
CREATE TABLE doc_exe ( column_a INT CONSTRAINT column_a_unUNIQUE) ; GO
ALTER TABLE doc_exe ADD
-- Add a PRIMARY KEY identity column.column_b INT IDENTITY
-
8/13/2019 Sq l Server Final Soft Copy
29/183
CONSTRAINT column_b_pk PRIMARY KEY,
-- Add a column that references another column in the same table.
column_c INT NULL
CONSTRAINT column_c_fkREFERENCES doc_exe(column_a),
-- Add a column with a constraint to enforce that
-- nonnull data is in a valid telephone number format. column_d VARCHAR (16) NULL
CONSTRAINT column_d_chk
CHECK (column_d LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]' OR
column_d LIKE
'([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]'),
-- Add a nonnull column with a default.
column_e DECIMAL(3,3) CONSTRAINT column_e_default DEFAULT .081 ; GO
EXEC sp_help doc_exe ; GO
DROP TABLE doc_exe ; GO
H. Adding a nullable column with default values
The following example adds a nullable column with a DEFAULT definition, and uses WITH
VALUES to provide values for each existing row in the table. If WITH VALUES is not used,
each row has the value NULL in the new column.
Use VideoRentalSystemgo
CREATE TABLE doc_exf ( column_a INT) ; GO
INSERT INTO doc_exf VALUES (1) ;
-
8/13/2019 Sq l Server Final Soft Copy
30/183
GO
ALTER TABLE doc_exfADD AddDate smalldatetime NULL CONSTRAINT AddDateDflt
DEFAULT GETDATE() WITH VALUES ; GO
SELECT * FROM doc_exfgo
DROP TABLE doc_exf ; GO
I. Disabling and re-enabling a constraintThe following example disables a constraint that limits the salaries accepted in the data. NOCHECK CONSTRAINT is used with ALTER TABLE to disable the constraint and allow for
an insert that would typically violate the constraint. CHECK CONSTRAINT re-enables the
constraint.
use VideoRentalSystem
go
CREATE TABLE cnst_example
(id INT NOT NULL, name VARCHAR (10) NOT NULL,
salary MONEY NOT NULL CONSTRAINT salary_cap CHECK (salary
-
8/13/2019 Sq l Server Final Soft Copy
31/183
-- Re-enable the constraint and try another insert; this will fail.ALTER TABLE cnst_example CHECK CONSTRAINT salary_cap; INSERT INTO cnst_example VALUES (4,'Eric James',110000) ;
J. Dropping a constraint
The following example removes a UNIQUE constraint from a table.
Use VideoRentalSystemgo
CREATE TABLE doc_exc ( column_a INT CONSTRAINT my_constraint UNIQUE) ; GO
ALTER TABLE doc_exc DROP CONSTRAINT my_constraint ; GO
DROP TABLE doc_exc ; GO
M. Creating a PRIMARY KEY constraint with index options
The following example creates the PRIMARY KEY constraintPK_TransactionHistoryArchive_TransactionID and sets the options FILLFACTOR, ONLINE,
and PAD_INDEX. The resulting clustered index will have the same name as the constraint.
USE AdventureWorks2008R2;GOALTER TABLE Production.TransactionHistoryArchive WITH NOCHECKADD CONSTRAINT PK_TransactionHistoryArchive_TransactionID PRIMARY KEY CLUSTERED(TransactionID)WITH (FILLFACTOR = 75, ONLINE = ON, PAD_INDEX = ON);GO
N. Dropping a PRIMARY KEY constraint in the ONLINE mode
The following example deletes a PRIMARY KEY constraint with the ONLINE option set to ON.
-
8/13/2019 Sq l Server Final Soft Copy
32/183
USE AdventureWorks2008R2;GOALTER TABLE TransactionHistoryArchiveDROP CONSTRAINT PK_TransactionHistoryArchive_TransactionIDWITH (ONLINE = ON);
GO
O. Adding and dropping a FOREIGN KEY constraint
The following example creates the table ContactBackup, and then alters the table, first by adding
a FOREIGN KEY constraint that references the table Person, then by dropping the FOREIGN
KEY constraint.
USE AdventureWorks2008R2 ;
GOCREATE TABLE ContactBackup(ContactID int) ;GOALTER TABLE ContactBackupADD CONSTRAINT FK_ContactBacup_Contact FOREIGN KEY (ContactID)
REFERENCES Person (BusinessEntityID) ;ALTER TABLE ContactBackupDROP CONSTRAINT FK_ContactBacup_Contact ;GODROP TABLE ContactBackup ;
P. Changing the size of a column
The following example increases the size of a varchar column and the precision and scale of a
decimal column. Because the columns contain data, the column size can only be increased. Also
notice that col_a is defined in a unique index. The size of col_a can still be increased because thedata type is a varchar and the index is not the result of a PRIMARY KEY constraint.
javascript:CodeSnippet_CopyCode('CodeSnippetContainerCode18'); IF OBJECT_ID ( 'dbo.doc_exy', 'U' ) IS NOT NULL
DROP TABLE dbo.doc_exy;GO
-- Create a two-column table with a unique index on the varchar column.CREATE TABLE doc_exy ( col_a varchar(5) UNIQUE NOT NULL, col_b decimal (4,2));GOINSERT INTO doc_exy VALUES ('Test', 99.99);GO-- Verify the current column size.SELECT name, TYPE_NAME(system_type_id), max_length, precision, scaleFROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.doc_exy');GO-- Increase the size of the varchar column.
-
8/13/2019 Sq l Server Final Soft Copy
33/183
ALTER TABLE doc_exy ALTER COLUMN col_a varchar(25);GO-- Increase the scale and precision of the decimal column.ALTER TABLE doc_exy ALTER COLUMN col_b decimal (10,4);GO-- Insert a new row.INSERT INTO doc_exy VALUES ('MyNewColumnSize', 99999.9999) ;GO-- Verify the current column size.SELECT name, TYPE_NAME(system_type_id), max_length, precision, scaleFROM sys.columns WHERE object_id = OBJECT_ID(N'dbo.doc_exy');
Insert Command
Use VideoRentalSystemgo
exec sp_help t1 go INSERT INTO T1(col1, col2,col3) SELECT 1,'First' ,1 UNION ALL
SELECT 2,'Second' ,2 UNION ALL SELECT 3,'Third' ,3
UNION ALL SELECT 4, 'Fourth' ,4 UNION ALL
SELECT 5,'Fifth' ,5 GO Select * from T1go
------------------------------------*
INSERT INTO T1(col1, col2,col3) VALUES( 1,'First' ,1), (2,'Second' ,2), ( 3,'Third' ,3), ( 4, 'Fourth' ,4),
(5,'Fifth' ,5) GO
-
8/13/2019 Sq l Server Final Soft Copy
34/183
Renaming column and table:
The script for renaming any column :
Exec sp_RENAME 'TableName.[OldColumnName]' ,'[NewColumnName]', 'COLUMN'
The script for renaming any object (table, sp etc) :
Exec sp_RENAME '[OldTableName]' , '[NewTableName]'
Renaming a database:
EXEC sp_renamedb 'oldName', 'newName'
COMMIT: Marks the end of a successful implicit or explicit transaction. If
@@TRANCOUNT is 1, COMMIT TRANSACTION makes all data modifications
performed since the start of the transaction a permanent part of the database, freesthe resources held by the transaction, and decrements @@TRANCOUNT to 0. If
@@TRANCOUNT is greater than 1, COMMIT TRANSACTION decrements@@TRANCOUNT only by 1 and the transaction stays active.
A. Committing a transaction
The following example deletes a job candidate.
Copy USE AdventureWorks2008R2;GOBEGIN TRANSACTION;GO
DELETE FROM HumanResources.JobCandidateWHERE JobCandidateID = 13;GOCOMMIT TRANSACTION;GO
-
8/13/2019 Sq l Server Final Soft Copy
35/183
B. Committing a nested transaction
The following example creates a table, generates three levels of nested transactions, and then
commits the nested transaction. Although each COMMIT TRANSACTION statement has a
transaction_name parameter, there is no relationship between the COMMIT TRANSACTION
and BEGIN TRANSACTION statements. The transaction_name parameters are simplyreadability aids to help the programmer ensure that the proper number of commits are coded to
decrement @@TRANCOUNT to 0 and thereby commit the outer transaction.
USE AdventureWorks2008R2;GOIF OBJECT_ID(N'TestTran',N'U') IS NOT NULL
DROP TABLE TestTran;GOCREATE TABLE TestTran (Cola int PRIMARY KEY, Colb char(3));GO-- This statement sets @@TRANCOUNT to 1.BEGIN TRANSACTION OuterTran;GOPRINT N'Transaction count after BEGIN OuterTran = '
+ CAST(@@TRANCOUNT AS nvarchar(10));GOINSERT INTO TestTran VALUES (1, 'aaa');GO-- This statement sets @@TRANCOUNT to 2.BEGIN TRANSACTION Inner1;GOPRINT N'Transaction count after BEGIN Inner1 = '
+ CAST(@@TRANCOUNT AS nvarchar(10));GOINSERT INTO TestTran VALUES (2, 'bbb');GO-- This statement sets @@TRANCOUNT to 3.BEGIN TRANSACTION Inner2;GOPRINT N'Transaction count after BEGIN Inner2 = '
+ CAST(@@TRANCOUNT AS nvarchar(10));GOINSERT INTO TestTran VALUES (3, 'ccc');GO-- This statement decrements @@TRANCOUNT to 2.-- Nothing is committed.COMMIT TRANSACTION Inner2;GOPRINT N'Transaction count after COMMIT Inner2 = '
+ CAST(@@TRANCOUNT AS nvarchar(10));
-
8/13/2019 Sq l Server Final Soft Copy
36/183
GO-- This statement decrements @@TRANCOUNT to 1.-- Nothing is committed.COMMIT TRANSACTION Inner1;GOPRINT N'Transaction count after COMMIT Inner1 = '
+ CAST(@@TRANCOUNT AS nvarchar(10));GO-- This statement decrements @@TRANCOUNT to 0 and-- commits outer transaction OuterTran.COMMIT TRANSACTION OuterTran;GOPRINT N'Transaction count after COMMIT OuterTran = '
+ CAST(@@TRANCOUNT AS nvarchar(10));GO
ROLLBACK:
ROLLBACK TRANSACTION erases all data modifications made from the startof the transaction or to a savepoint. It also frees resources held by the transaction.
ROLLBACK TRANSACTION without a savepoint_name or transaction_name rolls back to the
beginning of the transaction. When nesting transactions, this same statement rolls back all inner
transactions to the outermost BEGIN TRANSACTION statement. In both cases, ROLLBACKTRANSACTION decrements the @@TRANCOUNT system function to 0. ROLLBACK
TRANSACTION savepoint_name does not decrement @@TRANCOUNT.
USE TempDB;
GO
CREATE TABLE ValueTable ([value] int)
GO
DECLARE @TransactionName varchar(20) = 'Transaction1';
--These statements start a named transaction,
--insert a two records, and then roll back
--the transaction named in the variable
--@TransactionName.
BEGIN TRAN @TransactionName
INSERT INTO ValueTable VALUES(1)
-
8/13/2019 Sq l Server Final Soft Copy
37/183
INSERT INTO ValueTable VALUES(2)
ROLLBACK TRAN @TransactionName
INSERT INTO ValueTable VALUES(3)
INSERT INTO ValueTable VALUES(4)
SELECT * FROM ValueTable
DROP TABLE ValueTable
--Results--value---------------3--4
Whenever you execute a COMMIT TRANSACTION statement, any transactionname after the statement is ignored. The only thing a COMMIT TRANSACTION
statement does is reduce the @@trancount variable by 1. If this makes@@trancount = 0, then all database modifications are committed.
CREATE TABLE TestTran (Cola INT PRIMARY KEY, Colb CHAR(3))
GO
BEGIN TRANSACTION OuterTran – @@TRANCOUNT set to 1.GOINSERT INTO TestTran VALUES (1, „aaa‟)
GO
BEGIN TRANSACTION Inner1 – @@TRANCOUNT set to 2.
GOINSERT INTO TestTran VALUES (2, „bbb‟)
GOBEGIN TRANSACTION Inner2 – @@TRANCOUNT set to 3.
GOINSERT INTO TestTran VALUES (3, „ccc‟)
GOCOMMIT TRANSACTION Inner2 – Decrements @@TRANCOUNT to 2.
– Nothing committed. – ROLLBACK TRANSACTION Inner1
GO
-
8/13/2019 Sq l Server Final Soft Copy
38/183
COMMIT TRANSACTION Inner1 – Decrements @@TRANCOUNT to 1.
– Nothing committed.GO
COMMIT TRANSACTION OuterTran – Decrements @@TRANCOUNT to 0.
– Commits outer transaction OuterTran.GO
DROP TABLE TestTran
The only transaction name that SQL Server cares about is OuterTran. It‟s fine to label Inner1
and Inner2 transactions for other developers, but SQL Server does not use them.Also, the COMMIT TRANSACTION statement does not use the transaction name.
Only a ROLLBACK uses the transaction name, and only the outermost transactionname. For example, trying to do ROLLBACK TRANSACTION Inner1 where it is
commented out in the code snippet above would not work.
Committing inner transactions is ignored by Microsoft® SQL Server™. The
transaction is either committed or rolled back based on the action taken at the end
of the outermost transaction. If the outer transaction is committed, the inner nestedtransactions are also committed. If the outer transaction is rolled back, then all
inner transactions are also rolled back, regardless of whether or not the innertransactions were individually committed.
To List all the databases on the server:
EXEC sp_databases
To list fields in a table :
sp_help tablename
Eg:sp_help studentTable
Or
SELECT tablenameFROM DBName.sys.tables;
-
8/13/2019 Sq l Server Final Soft Copy
39/183
To the get the Tables count in the DB
SELECT Count(*)FROM DBName.sys.tables;
By default we can find the created date of all tables also
SELECT name,Create_DateFROM DBName.sys.tables;
Inserting Records Into Table containing Self-reference
USE VideoRentalSystemgo
CREATE TABLE Emp
( EmpID int PRIMARY KEY, EmpName varchar (30), MgrID int FOREIGN KEY REFERENCES Emp(EmpID) )
GO
INSERT dbo.Emp VALUES( 1, 'President', NULL) go
INSERT dbo.Emp Values(2, 'Vice President', 1) go
INSERT dbo.Emp values( 3, 'CEO', 2) go
INSERT dbo.Emp values( 4, 'CTO', 2) go
INSERT dbo.Emp values( 5, 'Group Project Manager', 4) go
-
8/13/2019 Sq l Server Final Soft Copy
40/183
The UPDATE command
UPDATE tableName SET Field1= 'val1', Field2 = val2, Field3 = val3
WHERE Field4 = val4
The DELETE command
Delete From Table-name --> Deletes all the records Delete From Table-name where condition --> Deletes only those records
that meet the criteria
Using OUTPUT clause with insert,update
and delete commands:
Use Mycompany
go --Select * from customer --go
insert into MyCompany.dbo.customeroutput inserted.CustId,inserted.CustName,inserted.CustCity values (400,'John','Chennai')
go
update customer set CustName='xxxxx',CustCity='yyyy' output inserted.CustName,inserted.CustCity where CustId=300
go
-
8/13/2019 Sq l Server Final Soft Copy
41/183
update customer set CustName='xxxxx',CustCity='yyyy' output inserted.* where CustId=300 go
delete from customer output deleted.* where CustId >= 300 go
Queries:
List All the distributors
Select * from Distributor
go
Show number and phone belonging to all distributors
Select DistributorNum,Phone from Distributor
go
Show Id,First name and Last name of all customers
Select CustomerId,Fname,Lname from Customer Go
Show First Name, Id and Last Name of all customers
Select FName,CustomerId,LName from Customer Go
Display Id and City of all customers
-
8/13/2019 Sq l Server Final Soft Copy
42/183
Select CustomerId,City from Customer
go
Show all the details of all the customers:
Select CustomerId,FName,LName,Phone,Street,City,ZipCode from customer go
--Select * from Customer--go
Coulmn-aliasing:
Show all the details of all the distributors. In the report, change first and secondfiled names as Distributor Number and Title respecitvely
Select DistributorNum as [Distributor Number],DistributorName as [Title],Phonefrom Distributor
go
Prefixing Column name with Table name
Select Distributor .DistributorNum,Distributor .DistributorName,Distributor .Phone from Distributor
Table aliasing:
Select Dist.DistributorNum,Dist.DistributorName,Dist.Phone from Distributor Dist
Conditional Retrieval:
List the details of all those customers who live in LA
Select * from Customer where City='LA'
-
8/13/2019 Sq l Server Final Soft Copy
43/183
go
Show First name and Last name of that customer whose id is 200334
Select FName,LName from Customer where CustomerId=200334
go
Show number,title,distributor number and price of all those videos whose prices
are greater than or equal to 3.0
Select VideoNum,Vtitle, DistNum, Price from Video where Price >= 3.0go
Select VideoNum,Vtitle, DistNum, Price from Video where Price >= 1.0 and Price
-
8/13/2019 Sq l Server Final Soft Copy
44/183
JOB VARCHAR (9) NOT NULL, MGR NUMERIC(4) NULL, HIREDATE DATETIME NOT NULL, SAL NUMERIC(7, 2) NOT NULL CHECK (SAL
-
8/13/2019 Sq l Server Final Soft Copy
45/183
An operator is a symbol specifying an action that is performed on one or more
expressions. The following tables lists the operator categories that SQL Serveruses.
Arithmetic Operators Logical Operators
Assignment Operator Scope Resolution Operator
Bitwise Operators Set Operators
Comparison Operators String Concatenation Operator
Compound Operators Unary Operators
Operators have the precedence levels shown in the following table. An operator on
higher levels is evaluated before an operator on a lower level.
Level Operators
1 ~ (Bitwise NOT)
2 * (Multiply), / (Division), % (Modulo)
3
+ (Positive), - (Negative), + (Add),
(+ Concatenate), - (Subtract), & (Bitwise AND),
^ (Bitwise Exclusive OR), | (Bitwise OR)
4 =, >, =, , !< (Comparison operators)
5 NOT
(Logical)
6 AND
(Logical)
7 ALL, ANY, BETWEEN, IN, LIKE, OR, EXISTS, SOME (Logical)
8 = (Assignment)
Note:
The plus (+) and minus (-) operators can also be used to perform arithmeticoperations on datetime and smalldatetime values.
http://msdn.microsoft.com/en-us/library/ms187716.aspxhttp://msdn.microsoft.com/en-us/library/ms189773.aspxhttp://msdn.microsoft.com/en-us/library/ms188343.aspxhttp://msdn.microsoft.com/en-us/library/dd206995.aspxhttp://msdn.microsoft.com/en-us/library/ms176122.aspxhttp://msdn.microsoft.com/en-us/library/ff848745.aspxhttp://msdn.microsoft.com/en-us/library/ms188074.aspxhttp://msdn.microsoft.com/en-us/library/ms190301.aspxhttp://msdn.microsoft.com/en-us/library/cc645922.aspxhttp://msdn.microsoft.com/en-us/library/ms188400.aspxhttp://msdn.microsoft.com/en-us/library/ms188400.aspxhttp://msdn.microsoft.com/en-us/library/cc645922.aspxhttp://msdn.microsoft.com/en-us/library/ms190301.aspxhttp://msdn.microsoft.com/en-us/library/ms188074.aspxhttp://msdn.microsoft.com/en-us/library/ff848745.aspxhttp://msdn.microsoft.com/en-us/library/ms176122.aspxhttp://msdn.microsoft.com/en-us/library/dd206995.aspxhttp://msdn.microsoft.com/en-us/library/ms188343.aspxhttp://msdn.microsoft.com/en-us/library/ms189773.aspxhttp://msdn.microsoft.com/en-us/library/ms187716.aspx
-
8/13/2019 Sq l Server Final Soft Copy
46/183
SQL Server provides the following set operators also. Set operators combine
results from two or more queries into a single result set.
EXCEPT
INTERSECT
UNION
The scope resolution operator :: provides access to static members of a compound
data type. A compound data type is one that contains multiple simple data typesand methods.
Compound operators execute some operation and set an original value to the result
of the operation. For example, if a variable @x equals 35, then @x += 2 takes theoriginal value of @x, add 2 and sets @x to that new value (37).
select * from employee where Sal >= 2000 AND Sal
-
8/13/2019 Sq l Server Final Soft Copy
47/183
select * from employee where hiredate between '17-DEC-1980' and '3-DEC-1981'
select * from employee where deptno = 10 or deptno = 20;
select * from employee where deptno in(10,20);
select * from employee where deptno NOT in(10,20);
select * from employee where comm is null
select empno,ename from employee order by empno
select ename,Sal from employee order by sal
select ename,Sal from employee order by sal,ename
select * from employee order by deptno, job
wrong: for displaying records of those employees who are managers and workingin 10 or 20
select * from employee where job='MANAGER' and deptno=10 or deptno=20order by deptno
select * from employee where deptno=10 or deptno=20 AND job='MANAGER'
order by deptno
Correct: select * from employee where job='MANAGER' and (deptno=10 or deptno=20)
order by deptno
select * from employee where ename='CLARK'
select ename from EMPLOYEE where ENAME='martin'
-
8/13/2019 Sq l Server Final Soft Copy
48/183
SELECT ename FROM employee
WHERE ename COLLATE Latin1_General_CS_AS = 'martin'
What is collation?
Collation refers to a set of rules that determine howdata is sorted and compared. Character data is sorted
according to rules that define the correct character sequence.
CREATE TABLE mytable
( mycolumn VARCHAR (10)
)
GO
INSERT mytable VALUES('Case')
GO
SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE'
SELECT mycolumn FROM mytable WHERE mycolumn='case'
You can alter your query by forcing collation at the column level:
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'caSE'
SELECT myColumn FROM myTableWHERE myColumn COLLATE Latin1_General_CS_AS = 'case'
SELECT myColumn FROM myTable
WHERE myColumn COLLATE Latin1_General_CS_AS = 'Case'
-- if myColumn has an index, you will likely benefit by adding
-- AND myColumn = 'case'
ALTER TABLE mytable
ALTER COLUMN mycolumn VARCHAR (10)
COLLATE Latin1_General_CS_ASGO
-
8/13/2019 Sq l Server Final Soft Copy
49/183
INSERT mytable VALUES('Case') SELECT mycolumn FROM mytable WHERE mycolumn='Case'
SELECT mycolumn FROM mytable WHERE mycolumn='caSE' SELECT mycolumn FROM mytable WHERE mycolumn='case'
CREATE TABLE mytable
(
mycolumn VARCHAR (10)COLLATE Latin1_General_CS_AS
) GO
use mastergocreate database BIN collate Latin1_General_BINgocreate database CI_AI_KS collate Latin1_General_CI_AI_KSgocreate database CS_AS_KS_WS collate Latin1_General_CS_AS_KS_WSgo
DELETE FROM TableName OUTPUT DELETED.Columns WHERE Condition(s)
Appendix A: Collation Suffixes
Suffix Meaning _BIN binary sort _CI_AI case-insensitive, accent-insensitive, kanatype-insensitive, width-insensitive
_CI_AI_WS case-insensitive, accent-insensitive, kanatype-insensitive, width-sensitive
-
8/13/2019 Sq l Server Final Soft Copy
50/183
_CI_AI_KS case-insensitive, accent-insensitive, kanatype-sensitive, width-insensitive
_CI_AI_KS_WS case-insensitive, accent-insensitive, kanatype-sensitive, width-sensitive
_CI_AS case-insensitive, accent-sensitive, kanatype-insensitive, width-insensitive _CI_AS_WS case-insensitive, accent-sensitive, kanatype-insensitive, width-sensitive
_CI_AS_KS case-insensitive, accent-sensitive, kanatype-sensitive, width-insensitive
_CI_AS_KS_WS case-insensitive, accent-sensitive, kanatype-sensitive, width-sensitive _CS_AI case-sensitive, accent-insensitive, kanatype-insensitive, width-insensitive _CS_AI_WS case-sensitive, accent-insensitive, kanatype-insensitive, width-sensitive
_CS_AI_KS case-sensitive, accent-insensitive, kanatype-sensitive, width-insensitive
_CS_AI_KS_WS case-sensitive, accent-insensitive, kanatype-sensitive, width-sensitive _CS_AS case-sensitive, accent-sensitive, kanatype-insensitive, width-insensitive
_CS_AS_WS case-sensitive, accent-sensitive, kanatype-insensitive, width-sensitive
_CS_AS_KS case-sensitive, accent-sensitive, kanatype-sensitive, width-insensitive
_CS_AS_KS_WS case-sensitive, accent-sensitive, kanatype-sensitive, width-sensitive
Note Kana sensitivity is set by default to insensitive. In other words, by default,
katakana and hiragana are treated as the same. Width sensitivity is also insensitive by
default. In other words, by default, full-width and half-width characters are treated asthe same.
select langid, alias, lcid, msglangid from sys.syslanguages
A collation is a set of rules defining a character set and its sorting rules. SQLServer support a large number of built-in collations. For example:
• Albanian_CI_AI_KS_WS - Albanian, case-insensitive (CI), accent-insensitive (AI),kanatype-sensitive (KS), width-sensitive (WS).
• Arabic_CI_AS_KS_WS - Arabic, case-insensitive, accent-sensitive, kanatype-sensitive,width-sensitive.
• French_CI_AI - French, case-insensitive, accent-insensitive, kanatype-insensitive,width-insensitive.
• Korean_Wansung_BIN - Korean-Wansung, binary sort.• SQL_Latin1_General_CP1250_CI_AS - Latin1-General, case-insensitive,
accent-sensitive, kanatype-insensitive, width-insensitive.
SELECT * FROM fn_helpcollations() GO
-
8/13/2019 Sq l Server Final Soft Copy
51/183
SQL Server Functions – Grouping Records –
Ordering Records - Partitioning Records
To support determinism and non-determinism, Transact-SQL provides two broad categories of
functions. A function that always returns the same or known value is referred to as deterministic.
A function whose returned value may depend on a condition is referred to as non-deterministic.
Cast Function:
In most cases, a value the user submits to your database is primarily considered a string. This is
convenient if that's what you are expecting. If the value the user provides must be treated assomething other than a string, for example, if the user provides a number, before using such a
value, you should first convert it to the appropriate type, that is, from a string to the expectedtype.
CAST(Expression AS DataType)
The Expression is the value that needs to be cast.
The DataType factor is the type of value we want to convert the Expression to.
Print Cast('121' As int)
Print Cast('1234' As Decimal(6,2))
Convert Function:
Like CAST(), the CONVERT() function is used to convert a value.
Unlike CAST(), CONVERT() can be used to convert a value from its original
type into a non-similar type.
For example, you can use CONVERT to cast a number into a string
and vice-versa.
The syntax of the CONVERT() function is:
CONVERT(DataType [ ( length ) ] , Expression)
Print Convert(int,125.66);
String based functions:
-
8/13/2019 Sq l Server Final Soft Copy
52/183
To get the length of a string, you can use the LEN() function.
Its syntax is:
int LEN(String )
select LEN('hello world')
print len('hello world')
If you have a string, to get the ASCII code of its leftmost character,
you can use the ASCII() function. Its syntax is:
int ASCII(String )
This function takes a string as argument and returns theASCII code of the first (the left) character of the string.
print Ascii('allen')
If you have the ASCII code of a character and want to find its actual character, you
can use the CHAR() function. Its syntax is:
char CHAR(int value)
This function takes an integer value as argument
and returns the ASCII equivalent of that number.
print Char (65)
When you receive a string, if you want to convert all of its characters to lowercase,
you can use the LOWER() function. Its syntax is:
varchar LOWER(String)
This function takes as argument a string. Any lowercase letter that is part of the string would not
change. Any letter that is part of the string would be converted to lowercase. Any other character
or symbol would be kept "as is". After conversion, the LOWER() function returns a new string.
print lower ('HELLO world9%')
A sub-string is a section gotten from a string. The idea is to isolate one or a groupof characters for any necessary reason.
A left sub-string is one or a group of characters retrieved from the left side of a known string. To
get the left sub-string of a string, you can use the LEFT() function. Its syntax is:
-
8/13/2019 Sq l Server Final Soft Copy
53/183
varchar LEFT(String , NumberOfCharacters)
This function takes two arguments.
The first argument specifies the original string.
The second argument specifies the number of characters from
the most-left that will constitute the sub-string.
After the operation, the LEFT() function returns a new
string made of the left character + the NumberOfCharacters
on its right from the String .
print left('system',3)
varchar RIGHT(String , NumberOfCharacters)
print right('system',3)
To replace one character or a sub-string from a string, you can use theREPLACE() function. Its syntax is:
varchar REPLACE(String , FindString , ReplaceWith)
print replace('system','sys','xxxx')
Returns part of a character, binary, text, or image expression. Formore information about the valid Microsoft® SQL Server™ data types
that can be used with this function, see Data Types.Syntax
SUBSTRING ( expression , start , length )Arguments
expression
Is a character string, binary string, text, image, a column, or anexpression that includes a column. Do not use expressions thatinclude aggregate functions.
start
Is an integer that specifies where the substring begins.
-
8/13/2019 Sq l Server Final Soft Copy
54/183
length
Is a positive integer that specifies how many characters or bytesof the expression will be returned. If length is negative, an erroris returned.
This example shows how to return only a portion of a character string.From the authors table, this query returns the last name in one columnwith only the first initial in the second column.
USE pubsSELECT au_lname, SUBSTRING(au_fname, 1, 1)FROM authorsORDER BY au_lname
Here is how to display the second, third, and fourth characters ofthe string constant abcdef.
SELECT x = SUBSTRING('abcdef', 2, 3)
Here is the result set:
x----------bcd
(1 row(s) affected)
Arithmetic Functions:
SIGN(Expression)
print sign(125)
print sign(-125) print sign(null)
To get the absolute value of a number, you can use the ABS() function. Its syntax
is:
ABS(Expression)
print abs(-1567.77789)
-
8/13/2019 Sq l Server Final Soft Copy
55/183
print abs('-12.5')
The ceiling of a number is the closest
integer that is greater than the
number which is specified as argument.
The ceiling of 12.155 is 13 because 13
is the closest integer greater than or equal to 12.155.
The ceiling of – 24.06 is – 24.
To get the ceiling of a number, Transact-SQL provides the CEILING() function. Its syntax is:
CEILING(Expression)
This function takes as argument a number or an expression that can evaluate to a number. After
the conversion, if the function succeeds, it returns a double-precision number that is greater thanor equal to Expression.
print ceiling(12.456)
print ceiling(-24.06)
Consider two decimal numbers such as
128.44 and -36.72. The number 128.44 is
between 128 and 129 with 128 being the lower.
The number – 36.72 is between – 37 and – 36 with – 37
being the lower.
The lowest but closest integer value of a number
Which is given as argument to it. Based on this, the floor of 128.44 is 128. The
floor of – 36.72 is – 37.
To support finding the floor of a number, Transact-SQL provides the FLOOR() function. Itssyntax is:
FLOOR(Expression)
The FLOOR() function takes as argument a numeric
value or an expression that can be evaluated to a number.
print floor (128.44)
-
8/13/2019 Sq l Server Final Soft Copy
56/183
print floor (-36.72)
To calculate the exponential value of a number, Transact-SQL provides the EXP()
function. Its syntax is:
EXP(Expression)
This function takes one argument as a number or an expression that can be evaluated to a
number.
print exp(6.48)
The power of a number is the value of that number when raised to another number.
This is done using the following formula:
ReturnValue = xy
To support finding the power of a number, Transact-SQL provides the POWER() function. Its
syntax is:
POWER(x, y)
This function takes two required arguments. The first argument, x, is used as the base number to
be evaluated. The second argument, y, also called the exponent, will raise x to this value.
print power (5,2) print power (5,2.1) print power (2.667,8)
To assist with finding the natural logarithm of a number, Transact-SQL providesthe LOG() function. Its syntax is:
LOG(Expression)
This function takes one argument as a number or an expression that can evaluate to a number.After the calculation, it returns the natural logarithm of the argument.
print log(10) print log(48.16)
To calculate the base 10 logarithm of a number, Transact-SQL provides theLOG10() function. Its syntax is:
LOG10(Expression)
The number to be evaluated is passed as the argument X. The function returns the logarithm on base 10 using the formula:
-
8/13/2019 Sq l Server Final Soft Copy
57/183
y = log10x
which is equivalent to
x = 10y
print log10(10) print log10(48.16)
To support the calculation of a square root, Transact-SQL provides the SQRT()
function. Its syntax is:
SQRT(Expression)
This function takes one argument as a positive decimal number. If the number is positive, after
the calculation, the function returns the square root of x.
print sqrt(25) print sqrt(27.999)
Measure based function:
The letter п, also written as PI, is a number used in various mathematicalcalculations. Its approximate value is 3.1415926535897932. The calculator of
Microsoft Windows represents it as 3.1415926535897932384626433832795. Toget the value of PI, Transact-SQL provides the PI() function. Its syntax is simply:
PI()
print PI()
If you know the value of an angle in degrees and you want to get the radians,
Transact-SQL provides the RADIANS() function. Its syntax is:
RADIANS(Expression)
This function takes as argument a value in degrees. If it succeeds in its calculation, it returns the
radians value.
print radians(180)
If you know the radians but want to get the degrees of an angle, you can use theDEGREES() function. Its syntax is:
DEGREES(Expression)
This function takes as argument a value in radians. If it succeeds, it returns the equivalent value
-
8/13/2019 Sq l Server Final Soft Copy
58/183
in degrees.
print degrees(4)
To get the cosine of an angle, you can call the COS() function. Its syntax is:
COS(Expression)
The angle to be considered is passed as the argument to this function. The function thencalculates and returns its cosine.
print cos(45)
To get the sine of an angle, you can use the SIN() function whose syntax is:
SIN(Expression)
The angle to be considered is passed as the argument. After its calculation, the function returns
the sine of the angle between – 1 and 1.
print sin(60)
To get the tangent of an angle, you can use the TAN() function of Transact-SQL.Its syntax is:
TAN(Expression)
Date and time based functions:
To get the current date and the current time of the computer that a user is using,you can use the GETDATE() function of Transact-SQL. Its syntax is:
GETDATE()
This function simply returns the current date and time of the operating system.
print GetDate()
One of the primary operations you may want to perform on a date or a time valuewould consist of adding a value to it. To support this operation, Transact-SQL
provides the DATEADD() function. Its syntax is:
DATEADD(TypeOfValue, ValueToAdd , DateOrTimeReferenced )
The third argument to this function is the value of a date or a time on which the operation will be
performed. It can be a constant value in the form of 'year/month/day' for a date or 'hour:minutes
-
8/13/2019 Sq l Server Final Soft Copy
59/183
AM/PM' for a time.
The second argument is the value that will be added. It should be a constant integer, such as 8, or
a floating point value, such as 4.06.
When calling this function, you must first specify the type of value that you want to add. This
type is passed as the first argument. It is used as follows:
• If you want to add a number of years to a date, specify the TypeOfValue as Year or yy, oryyyy (remember that SQL is case-insensitive).
print DATEADD(yy,4,GetDate()) print DATEADD(mm,4,GetDate()) print DATEADD(dd,4,GetDate()) print DATEADD(yy,8,'2010-04-27')
select DATEADD(yy,8,'2010-04-27') as [resultant date]
If you want to add a number of quarters of a year to a date, specify the
TypeOfValue as Quarter or d, or qq.
In the same way, you can add values as follows:
Type of
Value Abbreviation As a result
Year yy
A number of years will be added to the date value yyyy
quarter q
A number of quarters of a year will be added to the date value
qq Month
m A number of months will be added to the date value
mm
dayofyear y
A number of days of a year will be added to the date value dy
Day d
A number of days will be added to the date value dd
Week wk
A number of weeks will be added to the date value ww
Hour hh A number of hours will be added to the time value
minute
n
A number of minutes will be added to the time value mi
second s
A number of seconds will be added to the time value ss
millisecond ms A number of milliseconds will be added to the time value
-
8/13/2019 Sq l Server Final Soft Copy
60/183
Another regular operation performed on a date or a time value consists of gettingthe number of units that has elapsed in the range of two dates or two time values.
To support this operation, Transact-SQL provides the DATEDIFF() function. Its
syntax is: DATEDIFF(TypeOfValue, StartDate, EndDate)
This function takes three arguments. The second argument is the starting date or the starting time
of the range to be considered. The third argument is the end or last date or time of the consideredrange. You use the first argument to specify the type of value you want the function to produce.
This argument uses the same value as those of the DATEADD() function:
Type of
Value Abbreviation As a result
Year yy The function will return the number of years that have elapsed
between the start and the end dates yyyy
quarter q The function will return the number of quarters of a year that have
elapsed between the start and the end dates qq
Month m The function will return the number of months that have elapsed
between the start and the end dates mm
dayofyear y The function will return the number of days of a year that have
elapsed between the start and the end dates dy
Day d The function will return the number of days that have elapsed
between the start and the end dates dd
Week wk The function will return the number of weeks that have elapsed
between the start and the end dates ww
Hour hh The function will return the number of hours that have elapsed between the start and the end times or dates
minute n The function will return the number of minutes that have elapsed
between the start and the end times or dates mi
second s The function will return the number of seconds that have elapsed
between the start and the end times or dates ss
millisecond ms The function will return the number of milliseconds that have elapsed
between the start and the end times or dates
print DATEDIFF(yy,'2000-11-10',GetDate())
DATENAME
Returns a character string that represents thespecified datepart of the specified date
Syntax:
DATENAME ( datepart , date )
-
8/13/2019 Sq l Server Final Soft Copy
61/183
SELECT DATENAME(year, '2011-DEC-24 12:10:30.123')
,DATENAME(month, '2011-DEC-24 12:10:30.123')
,DATENAME(day, '2011-DEC-24 12:10:30.123'),DATENAME(dayofyear, '2011-DEC-24 12:10:30.123')
,DATENAME(weekday, '2011-DEC-24 12:10:30.123')
,DATENAME(hour, '2011-DEC-24 12:10:30.123')
,DATENAME(minute, '2011-DEC-24 12:10:30.123')
,DATENAME(second, '2011-DEC-24 12:10:30.123')
,DATENAME(millisecond, '2011-DEC-24 12:10:30.123')
go
DATEPART
Returns an integer that represents the specified datepartof the specified date.
syntax:
DATEPART ( datepart , date )
SELECT DATEPART(year, '2011-DEC-24 12:10:30.123')
,DATEPART(month, '2011-DEC-24 12:10:30.123')
,DATEPART(day, '2011-DEC-24 12:10:30.123')
,DATEPART(dayofyear, '2011-DEC-24 12:10:30.123')
,DATEPART(weekday, '2011-DEC-24 12:10:30.123')
,DATEPART(hour, '2011-DEC-24 12:10:30.123')
,DATEPART(minute, '2011-DEC-24 12:10:30.123')
,DATEPART(second, '2011-DEC-24 12:10:30.123')
,DATEPART(millisecond, '2011-DEC-24 12:10:30.123')
go
DAY(),MONTH(),YEAR()
Returns an integer representing the day (day of the
-
8/13/2019 Sq l Server Final Soft Copy
62/183
month),the month and the year of the specified date.
DAY ( date )
SELECT DAY('2007-04-30 01:01:01.1234567-07:00')
goSELECT MONTH('2007-04-30 01:01:01.1234567-07:00')
go
SELECT YEAR('2007-04-30 01:01:01.1234567-07:00')
go
SELECT YEAR(0), MONTH(0), DAY(0)
go
Aggregate Functions:
Count: The database engine uses the Count() function to count the number of
occurrences of the category in the column and produces the total. This functionalso counts NULL values. The syntax of the Count() function is:
int COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )
This function takes one argument. To get the count of occurrences of a value, in the Criteria
section, select COUNT(*).
The Count() function returns an int value. If you are working on a large number of
records, you can call the Count_Big() function. Its syntax is:
bigint COUNT_BIG ( { [ ALL | DISTINCT ] expression } | * )
If the column holds numeric values:
• Sum: The Sum() function is used to sum up the values in the category. The syntax of theSum() function is:
Number SUM ( [ ALL | DISTINCT ] expression )
Avg: The sum of value in a category would be divided by the number of
occurrences in that category to get the average. The syntax of the Avg() function
-
8/13/2019 Sq l Server Final Soft Copy
63/183
is:
Number AVG ( [ ALL | DISTINCT ] expression )
Min: The lowest value of the category would be produced from the Min()
function. The syntax of this function is: DependsOnType MIN ( [ ALL | DISTINCT ] expression )
Max: The highest value of the category would be produced using the Max()
function. The syntax of this function is:
DependsOnType MAX ( [ ALL | DISTINCT ] expression )
StdDev: The StdDev() function is used to calculate the standard deviation
of all numeric values of a group. If there is no value or the same value in the
considered group, this function returns NULL. This means that there
should be at least two different values in the group.
The syntax of the StdDev() function is:
float STDEV ( [ ALL | DISTINCT ] expression )
Var: The Var() function calculates the statistical variance of
all numeric values of a group. If there is no value or the same value in the
considered group, this function returns NULL. The syntax of the
Var() function is:
float VAR ( [ ALL | DISTINCT ] expression )
select COUNT(comm) from EMPLOYEE; select COUNT(*) from EMPLOYEE; select COUNT(*) 'total_no_emp' from EMPLOYEE; select count(*) as [total number of employees]from EMPLOYEE ; select COUNT( job)from EMPLOYEE; select COUNT(distinct job) from EMPLOYEE;
-
8/13/2019 Sq l Server Final Soft Copy
64/183
select AVG(sal) from EMPLOYEE; select MIN(sal) from EMPLOYEE; select MAX(sal) from EMPLOYEE; select MAX(comm) from EMPLOYEE; select stdev(Sal) from EMPLOYEE; select VAR (sal) from EMPLOYEE;
use videorentalsystem
go
select * from video
go
Select SUM(Price) from Videogo
Select MIN(Price) from Video
go Select MAX(Price) from Video
go
Select AVG(Price) from Video
go
Select COUNT(Phone) from Customer go
Select COUNT(*) from Customergo
Select COUNT(VTitle) from Video
go Select COUNT(distinct VTitle) from Videogo
Select COUNT(VType) from Videogo
Select COUNT(Distinct VType) from Video
go
-
8/13/2019 Sq l Server Final Soft Copy
65/183
use videorentalsystem
go
Select * from Videogo
SElect City, COUNT(CustomerId) from customerGroup By City
go
SElect City, COUNT(CustomerId) As [Customer Id] from customerGroup By City
go
Select VType, COUNT(*) As [Num Of Videos] from Videogroup by VType
go Select DistNum, COUNT(*) As [Num of Videos] from Videogroup by DistNum
go Select VType,DistNum, COUNT(*) As [Num of Videos] from Video
group by VType,DistNum order by VType
go
Select DistNum, SUM(Price) as [Total Investment] from VideoGroup By DistNumgo
Select DistNum, Avg(Price) as [Average Price] from Video
Group By DistNumgo
RollUp:
It is used to calculate cumulative totals at the end of grouping
created based on the first column in group.
Select VType, Sum(Price) as [Total Invested] from VideoGroup By VType with RollUp go
-
8/13/2019 Sq l Server Final Soft Copy
66/183
Select isnull(VType,'Total') VType, Sum(Price) as [Total Invested] from VideoGroup By VType with RollUp go
Cube is used for calculating sub-totals at the end of each group
Select DistNum,isnull(VType,'Total'), Sum(Price) As [Total Cost] from Video
group by VType,DistNum with cube go
Compute and Compute by:
Compute by is like group byfor the reason that it also
groups records andapplies aggregate function on
each group but unlike group bycompute by allows us to retrieve
data from any column.
use videorentalsystem
go select * from video compute sum( price)
use videorentalsystemgo select * from video compute count(VideoNum)
Every column that is in by clause of compute by must be in order by
use videorentalsystemgo select * from video order by VType compute sum( price) by VType;
Over (partition by...)
-
8/13/2019 Sq l Server Final Soft Copy
67/183
Determines the partitioning and ordering of the rowset before the associated
window function is applied.
PARTITION BYDivides the result set into partitions. The aggregate function
is applied to each partition separately and computation
restarts for each partition.
while "compute by" will display the result of aggregate only once at end of thegroup where as over(partition by...) displays the results of aggregates with every
row in the group and not at the end of the group.
Find total cost of videos their type wise while displaying complete details of video.