Database Management System: SQL Server 2019 SQL and T-SQL
Database Management System: SQL Server 2019 SQL and T-SQL
SQL SERVER
SQL-(Different Sub Languages)
T-SQL-(SQL + Procedural Language)
Anonymous Block or Name Less Block
Stored or Named Block
Stored Procedure
Stored Functions
Stored Triggers
Business Intelligence Tools
SQL 2005 Click on Start and Run Type “SQLWB” (WB – WORK BENCH)
SQL 2008 Click on Start and Run Type “SSMS” (MS – MANAGEMENT STUDIO)
TYPES OF DATABASES
System Data Bases – (Master, Model, MSDB, TempDB, Resource(from 2008r2-Hidden))
o Master-Records all the system-level information for an instance of SQL Server
o Model-Is used as the template for all databases created on the instance of SQL Server.
Modifications made to the model database, such as database size, collation, recovery
model, and other database options, are applied to any databases created afterward.
o MSDB-Is used by SQL Server Agent for scheduling alerts and jobs.
o TempDB-Is a workspace for holding temporary objects or intermediate result sets.
o Resource-Is a read-only database that contains system objects that are included with
SQL Server. System objects are physically persisted in the Resource database, but they
logically appear in the sys schema of every database.
Sample Data Bases – 2000(Pubs, Northwind), 2005(Adventures, Adventures DW)
User Defined Data Bases – Created by Developers
CREATING A USER DEFINED DATABASE:
Database size in SQL SERVER 2000 was limited – 1048516TeraByte
Database size in SQL SERVER 2005 was unlimited.
Every database in SQL will be associated with two files.
DATA FILES (STORES DATA)
Primary Data File (.MDF Master Data File)
Secondary Data File (.NDF Next Data File)
LOG FILES (.LDF Stores Transaction Details)
Every database will have at least one primary data file
Tables will have logical data (ROWS & COLUMNS)
Primary files have physical data (BLOCKS)
Each block size will be of 8KB.
A Database can be connected 32000+ NDF files.
MDF will hold references of NDF files.
Having more NDF files will help to make backup process easy.
A Database can be associated by more than one .NDF & .LDF files.
The advantage of creating NDF files is to have easy backup of database
CREATING A DATABASE THROUGH – GUI
Step 1: Click on Object Explorer
Step 2: Click on Databases
Step 3: Right click on Database
Step 4: Click on to Create a New Database
Step 5: Enter DATABASE Name and Click Ok
Step 6: Specify the Size as .MDF Initial Size – 2MB Increment – 1MB MAX Size Unlimited
Step 7: Specify the Size as .NDF Initial Size – 1MB Increment – 10% MAX Size Unlimited
CREATING A DATABASE THROUGH QUERY/COMMAND
As Database creation is an administration related task, it should be carried out through MASTER system data
base
Syntax:
Example:
CREATE DATABASE TESTDB
ON (
NAME = TESTDB,
FILENAME = 'C:\SQL Server\MSSQL.1\MSSQL\DATA\TESTDB.MDF' ,
SQL Server 2019 Page: 7 SQL and T-SQL
SP_RENAMEDB 'TESTDB','DBTEST'
Dropping a Database:
Syntax:
DROP DATABASE < DATABASE_NAME >
DROP DATABASE TESTDB
Command to Use Navigate between Data Base’s
Syntax:
USE < DATABASE_NAME >
USE TESTDB
Command to get the Current Database Name - SELECT DB_NAME()
**SQL SERVER provides 1788 objects for every Database
SP_HELP: It will return list of predefined objects provided by MASTER Data Base to a User Defined
Database.
SP_HELPDB: This predefined Stored Procedure will provide list of database’s available in SQL
SERVER.
SP_HELPDB <DATABASE_NAME> - It will provide the complete information of the database.
STRUCTURE QUERY LANGUAGE – SQL
SQL is a language used to communicate with DATABASE SERVER.
Initially when SQL was introduced it was by name ‘SQUARE’ this language was modified and was
Released by a new name ‘SEQUEL’, later was renamed to SQL by removing all vowels in the SEQUEL.
SQUARE – SPECIFICATIONS OF QUERY AS RELATIONAL EXPRESSIONS
SEQUEL – STRUCTURED ENGLISH QUERY LANGUAGE
SQL – STURCTURED QUERY LANGUAGE
SQL is a product of IBM, later used by different companies and they made SQL available in there
Products according to their standards.
SQL is a called Common Database Language, since it gets understand by every RDBMS
SQL is a Command Based Language
SQL is an Insensitive Language
SQL is a Non Procedural Language
SQL Consist of following Sub Languages:
DATA QUERY OR RETRIVAL LANGUAGE {DQL OR DRL}
It is used to retrieve the data in different ways using “SELECT” Command.
DATA MANIPULATION LANGUAGE {DML}
Insertion of new rows, modifications to existing rows, removing unwanted rows, collectively known
As DATA MANIPULATION LANGUAGE, It includes INSERT, UPDATE, DELETE and MERGE (introduced in
2008)
TRANSACTION CONTROL LANGUAGE {TCL}
This language supports to make a transaction permanent in a database or supports to cancel the
Transaction. It includes COMMIT, ROLLBACK, SAVE commands.
DATA DEFINATION LANGUAGE {DDL}
This language is used to CREATE, ALTER and DROP Database objects like tables, views, indexes,
Synonyms, store procedures, store functions, stored triggers. It includes CREATE, ALTER, TRUNCATE,
DROP Commands.
DATA CONTROL LANGUAGE {DCL}
It is used to give rights on Database objects created by one user to get them access by other users it also
supports to cancel the given rights, It includes GRANT, REVOKE, DENY Commands.
To display list of User Defined Tables
SELECT NAME FROM SYS.TABLES
SELECT NAME FROM SYS.SYSOBJECTS WHERE XTYPE = 'U'
To display list of System Tables
SELECT NAME FROM SYS.SYSOBJECTS WHERE XTYPE = 'S'
SQL Server 2019 Page: 9 SQL and T-SQL
Operator Precedence:
Level Operators
1 ~ (Bitwise NOT)
2 * (Multiplication), / (Division), % (Modulus)
3 + (Positive), - (Negative), + (Addition), + (Concatenation), - (Subtraction), & (Bitwise AND),
^ (Bitwise Exclusive OR), | (Bitwise OR)
4 =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
5 NOT
6 AND
7 ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
8 = (Assignment)
Examples:
Q) Display all those EMPLOYEES who are working as CLERKS.
SELECT ENAME, JOB FROM EMP WHERE JOB = 'CLERK'
SELECT ENAME, JOB FROM EMP WHERE 'CLERK' =JOB
Q) Display all those EMPLOYEES who are working at Department Number 10
SELECT * FROM DEPT WHERE DEPTNO = 10
or
SELECT * FROM DEPT WHERE DEPTNO = '10'
Q) Display ENAME, JOB of those EMPLOYES who are not working as MANAGER
SELECT ENAME, JOB FROM EMP WHERE JOB != 'MANAGER'
Q) Display ENAME, JOB, and DEPTNO of those EMPLOYEES who are working as CLERK at DEPT NO 20.
SELECT * FROM EMP WHERE JOB = 'CLERK' AND DEPTNO = 20
Q) Display ENAME, JOB of those EMPLOYEES who are working as CLERK, ANALYST.
SELECT ENAME, JOB FROM EMP WHERE JOB = 'CLERK' OR JOB = 'ANALYST'
SELECT ENAME, JOB FROM EMP WHERE JOB IN ('CLERK','ANALYST')
Q) Display EMPNO, ENAME, DEPTNO of those EMPLOYEES who are working at 10, 30 Departments.
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE DEPT IN (10,30)
select * From emp where sal<=2000
select * From emp where 2000<=sal
IN:
This operator compares list of similar type values.
It works like “OR” Logical operator.
It can be used for any number of times.
The list should contain only one column values; multiple columns data is invalid.
Q) Display ENAME, JOB of those EMPLOYEES who are working as CLERK, ANALYST.
SELECT ENAME, JOB FROM EMP WHERE JOB IN ('CLERK','ANALYST')
SELECT ENAME, JOB FROM EMP WHERE ('CLERK','ANALYST') IN JOB
Q) Display EMPNO, ENAME, DEPTNO of those EMPLOYEES who are working at 10, 30 Departments.
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE DEPT IN (10,30)
Q) Display ENAME, SAL of EMPLOYEE SAL Greater than or equal to 2000 & SAL less than or equal to
SQL Server 2019 Page: 13 SQL and T-SQL
3000.
SELECT ENAME, SAL FROM EMP WHERE SAL >= 2000 AND SAL <=3000
SELECT ENAME, SAL FROM EMP WHERE SAL BETWEEN 2000 AND 3000
BETWEEN:
It is used to compare range of values (Numbers or dates)
Compares range of values including the specified data
It can also be used for any number of times
Q) Display ENAME, JOB, DEPTNO of those Employees who are not working as CLERK, ANALYST.
SELECT ENAME, JOB, DEPTNO FROM EMP WHERE JOB NOT IN ('CLERK','ANALYST')
Q) Display all those Employees whose salary is not in a range of 1000 and 3000.
SELECT * FROM EMP WHERE SAL NOT BETWEEN 1000 AND 3000
Q) Display all the Employees who are working as CLERK, ANALYST and SAL is greater than 1000.
SELECT * FROM EMP WHERE JOB = 'CLERK' OR 'ANALYST' AND SAL > 1000
SELECT * FROM EMP WHERE JOB IN ('CLERK','ANALYST') AND SAL > 1000
Q) Display ENAME, SAL, ANNUAL SAL of those Employees whose annual salary is in range of 18000
and 36000.
SELECT ENAME, SAL, SAL*12 AS ANNUALSAL FROM EMP
WHERE SAL*12 BETWEEN 18000 AND 36000
Q) Display ENAME, JOB, SAL, COMM and DEPTNO who are working as SALESMAN at DEPTNO 30 and
there commission is > half of their salary.
SELECT * FROM EMP WHERE JOB = 'SALESMAN' AND DEPTNO = 30 AND COMM > SAL/2
ANSI NULLS:
Working with IS Operator.
This operator is exclusively used for comparing NULL values.
It can be used any number of times.
SQL server also supports to compare the NULL values using relation operator.
Following SET Command should be used SET ANSI_NULLS OFF | ON [Default it is ON]
It should be turned to off when NULL value is compared with relational operator.
Q) Display all those Employees who are not earning commission.
SELECT * FROM EMP WHERE COMM IS NULL
Q) Display all those Employees whose are earning commission.
SELECT * FROM EMP WHERE COMM IS NOT NULL
SELECT * FROM EMP WHERE NOT COMM IS NULL
Q) Display EMPNO, ENAME & MGR of those Employees who don’t have manager to report.
SELECT * FROM EMP WHERE MGR IS NULL
Q) Display EMPNO, ENAME & MGR of those Employees who have managers to report.
SELECT * FROM EMP WHERE MGR IS NOT NULL
Q) Display EMPNO, ENAME, MGR, SAL and COMM of those Employees who have managers to report
and do not earn commission.
SELECT * FROM EMP WHERE MGR IS NOT NULL AND COMM IS NULL
SET ANSL_NULLS OFF
SELECT * FROM EMP WHERE COMM != NULL
SELECT * FROM EMP WHERE COMM = NULL
SELECT * FROM EMP WHERE MGR = NULL
SELECT * FROM EMP WHERE NULL = NULL
WILD CHARACTERS:
These characters are used to provide pattern matching when data is searched into a column
SQL SERVER supports to work with following characters.
“_” – it is used for single characters
“%” - it is used for group of characters
“-“– it is used for range of characters
“[]”- Escape character
LIKE OPERATOR:
SQL Server 2019 Page: 14 SQL and T-SQL
It is used for comparing the data which is enclosed with wild characters. It can be used for
any number of times.
This operator when compares the data using wild characters it should be enclosed in single
quotes.
Comparison to any type data should be placed in single quotes
If data in a column is enclosed with wild characters to search the data escape option should be
specified
SELECT * FROM EMP WHERE ENAME LIKE 'J%'
SELECT * FROM EMP WHERE ENAME LIKE '%S'
SELECT * FROM EMP WHERE ENAME LIKE 'J%S'
SELECT * FROM EMP WHERE ENAME LIKE '%A%'
SELECT * FROM EMP WHERE ENAME LIKE '%A%E%'
SELECT * FROM EMP WHERE ENAME LIKE 'J[_]%'
SELECT * FROM EMP WHERE ENAME LIKE '[a-klm]%'a%,b%,..j%,k%,l%,m%
SELECT * FROM EMP WHERE ENAME LIKE '[-aklm]%'-%,a%,k%...m%
SELECT * FROM EMP WHERE ENAME LIKE 'sm[iabc]'smi,sma,smb,smc
SELECT * FROM EMP WHERE ENAME LIKE '[smi]abc'sabc,mabc,iabc
SELECT * FROM EMP WHERE ENAME LIKE 'sm[ia]bc'smibc,smabc
SELECT * FROM EMP WHERE ENAME LIKE 'J\_%' ESCAPE '\'
**In ESCAPE we can use any characters except WILD CHARACTERS.
SELECT * FROM EMP WHERE ENAME LIKE '[A-F]%'
SELECT * FROM EMP WHERE ENAME NOT LIKE '[A-F]%'
SELECT * FROM EMP WHERE ENAME LIKE '[^A-F]%'
SELECT * FROM EMP WHERE ENAME LIKE '___'
SELECT * FROM EMP WHERE ENAME LIKE '%?_%' ESCAPE '?'
DISTINCT OPERATOR:
Eliminates duplicates.
Always arranges the data in ASCENDING ORDER.
It should be used immediately after SELECT command.
It includes NULL VALUES.
When multiple columns are used with DISTINCT operator it eliminates only if all the columns
contains duplicates.
If you are trying to use order by clause with distinct then the columns which you are used in the select
list those only you need use in order by clause
SELECT DISTINCT DEPTNO FROM EMP
SELECT DISTINCT JOB FROM EMP
SELECT DISTINCT COMM FROM EMP
SELECT DISTINCT MGR FROM EMP WHERE MGR IS NOT NULL
SELECT DISTINCT DEPTNO, JOB FROM EMP
SELECT DISTINCT DEPTNO, JOB FROM EMP order by DEPTNO
ORDER BY:
This clause is used to arrange the data in ASCENDING / DESCENDING order.
By default it arranges the data in ASCENDING order.
Order by clause will work after the execution of “SELECT” statement.
Order by clause will arrange the data in order at buffer location, hence it is temporary.
It can arrange the data in order based on COLUMN_NAME or COLUMN_ALIAS_NAME or
COLUMN_POSITION {according to query} to specify order type.
ASC ----- ASCENDING & DESC ---- DESCENDING
When multiple columns are used at ORDER BY clause. First column will be fully arranged in
order and other columns will be arranged based on previous column.
When multiple columns are used at ORDER BY clause, they can be specified with same order
SQL Server 2019 Page: 15 SQL and T-SQL
SINGLE ROW FUNCTION: This function will process one row at a time and returns one value.
Mathematical Functions
String Functions
Date & Time Functions
Data Conversion {Type Casting Functions}
Ranking Functions {Windows Functions}
Metadata Functions
Security Functions
JSON Functions
Other Functions
MULTIPLE ROW FUNCTION: This function will process multiple rows at a time and returns one value.
Aggregate Functions
SQL SERVER supports to work with 12 categories of Functions and they are found at following paths
Click on Object Explorer – Data Bases
SQL Server 2019 Page: 16 SQL and T-SQL
Select the Data Base – TESTDB(your own data base which is used to practice)
Check under Programmability Functions.
Check under System Functions.
MATHEMATICAL FUNCTIONS:
This function will take input as numbers and will return output as numbers
ABS (NUMBER) - returns unsigned value of a given number (Number - Argument or Parameter).
SELECT ABS(-890), ABS(17)
SQRT (NUMBER) - Returns square root of a given positive number.
SQUARE (NUMBER) - Returns square of a given value
POWER (NUMBER(Base), NUMBER(Exponent)) - It will find the power of a given number.
SELECT POWER (2,5)
SIGN ( NUMBER )
Returns 1 if a number is positive
Returns -1 if a number is negative
Returns 0 if a number is zero
PI() - Returns PI value
SIN (NUMBER) –
** By default these trigonometric functions will take input given in radians, hence radians should be
converted to degrees by a standard formula is PI ()/180
SELECT SIN (30* PI()/180)
Note: if Arg2 is –ve number it will round off Numeric part of given number. If it is +ve number it will truncate
decimal part
CEILING(NUMBER) – This function will increment a given number to its nearest integer. Based on
any digit in decimal points is greater than zero.
CEILING (123.000) ---- 123
CEILING (123.010) ---- 124
CEILING (123.456) ---- 124
CEILING (-123.456) ---- -123
DEGREES()-This function returns the corresponding angle, in degrees, for an angle specified in
radians
DEGREES(pi()/2)--90
RAND ( [ seed ] )
Rand()—Returns a random float value from 0 through 1
Rand(1)— 0.713591993212924 (it is a fixed values)
Rand(0)— 0.943597390424144 (it is a fixed values)
Note: If seed is not specified, the SQL Server Database Engine assigns a seed value at random. For a specified
seed value, the result returned is always the same
STRING FUNCTIONS: This are used to perform different operations on STRING DATA TYPE.
LEN(TEXT) - Returns the number of characters of the specified string expression, excluding trailing blanks.
SELECT ENAME, LEN(ENAME) FROM EMP WHERE LEN(ENAME) > 5
LOWER(STRING) – Converts characters to Lower case.
UPPER(STRING) – Converts characters to Upper case.
ASCII(STRING) – returns ASCII code of the given character
ASCII('A')----65
ASCII('P')----80
UNICODE( STRING ) – Returns UNICODE of a given string.
CHAR ( NUMBER ) – Returns character of a given ASCII code
CHAR (65) –- A {Only 0-255 characters are available}
CHAR (-1)—NULL
CHAR (256)--NULL
NCHAR(NUMBER)
NCHAR(256) {1-65535 Characters are available}
NCHAR(65536)--NULL
LEFT(STRING,NUMBER) – Extracts number of characters from left side of a string
LEFT('COMPUTER',3) ---- COM
LEFT('COMPUTER',-1) ---- Error
RIGHT( STRING, NUMBER) – Extracts number of characters from right side of a string
RIGHT('COMPUTER',3)-----TER
RIGHT('COMPUTER',-1)-- Error
SUBSTRING (STRING, STARTPOSITION, NUMBER OF CHAR’S) – It extracts required string
from a given string based on start position and number of characters.
SUBSTRING ('COMPUTER',4,3)—PUT
SUBSTRING ('COMPUTER',0,3)—CO
SUBSTRING ('COMPUTER',-1,3)—C
SUBSTRING ('COMPUTER',0,-3)—ERROR
LTRIM(STRING) - Removes blanks spaces from left side of a string.
RTRIM(STRING)- Removes blank spaces from right side of a string.
REPLICATE(STRING, NUMBER) - Displays a given string for n times.
REPLICATE('COMM',2)
REVERSE(STRING) - It will reverse a given string.
SELECT REVERSE('COMM')--- MMOC
REPLACE (STRING1, STRING2, STRING3)
String1 ---- given string, String2 ---- search string, String3 ---- replace string
REPLACE ('COMPUTER','UT','IR')
It will search for String2 in String1 and replaces with String3 at all occurrences of String 2 in String1
STUFF(STRING1, NUMBER1, NUMBER2, STRING2)
String1 --- Given String, Number 1--- Start Position, Number2 --- Number of Characters
String2 --- Replace
STUFF('COMPUTER',5,2,'IL') -- COMPILER
CHARINDEX(STRING1, STRING2, [NUMBER])
SQL Server 2019 Page: 18 SQL and T-SQL
String1 --- Search String, String2 --- Given String, Number --- Position
It will search for string1 in string2 and returns position of string1, if it exists else returns zero, by
default it will search from first character. It also supports to search for character/string after a
specific position
SELECT CHARINDEX('R','COMPUTER',7)
SELECT REPLICATE ('*', GRADE) FROM SALGRADE
PATINDEX ('%pattern%',expression)- Returns the starting position of the first occurrence of a pattern
in a specified expression, or zeros if the pattern is not found, on all valid text and character data types
SPACE ( integer_expression )- Returns a string of repeated spaces.
CONCAT-This function returns a string resulting from the concatenation, or joining, of two or more
string values in an end-to-end manner
SELECT CONCAT ( 'I am', 'not a ','Good Trainer') AS Result;
SELECT CONCAT ('I was born on ',22 ,'/','Dec') AS Result;
CONCAT_WS - This function returns a string resulting from the concatenation, or joining, of two or more string
values in an end-to-end manner. It separates those concatenated string values with the delimiter specified in
the first function argument. (CONCAT_WS indicates concatenate with separator.)
QUOTENAME- Returns a Unicode string with the delimiters added to make the input string a valid SQL Server
delimited identifier.
STR - Returns character data converted from numeric data.
STRING_AGG - Concatenates the values of string expressions and places separator values between them. The
separator is not added at the end of string.
STRING_ESCAPE - Escapes special characters in texts and returns text with escaped characters. STRING_ESCAPE
is a deterministic function.
STRING_SPLIT - A table-valued function that splits a string into rows of substrings, based on a specified
separator character.
TRANSLATE - Returns the string provided as a first argument after some characters specified in the second
argument are translated into a destination set of characters specified in the third argument.
Q) Display all the employees from the EMP table with half of the string in upper case and next string
in lower case
SELECT LEFT (ENAME, CEILING (LEN (ENAME)/2.0)) +
LOWER(RIGHT (ENAME, CEILING (LEN (ENAME)/2))) FROM EMP
Q) Display all Employees whose name contains 3rd Character as ‘L’.
SELECT ENAME FROM EMP WHERE SUBSTRING (ENAME, 3,1)= 'L'
SELECT ENAME FROM EMP WHERE CHARINDEX ('L', ENAME, 3) = 3
Q) Display all Employees whose name contains A at second occurrence.
SELECT ENAME FROM EMP
WHERE CHARINDEX ('A', ENAME, CHARINDEX ('A', ENAME) +1 !=0
DATE & TIME FUNCTIONS:
These functions are used to perform operations on date, time data type. When date type data is
retrieved it will be in the following format.
CENTURY: YEAR: MONTH: DATE: HOURS: MINUTES: SECONDS
GETDATE(): It returns current system DATE & TIME of the Server.
SELECT GETDATE()
CURRENT_TIMESTAMP-- Returns the current database system timestamp as a datetime value without
the database time zone offset. This value is derived from the operating system of the computer on which the
instance of SQL Server is running
GETUTCDATE()--Returns the current database system timestamp as a datetime value. The database
time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This
value is derived from the operating system of the computer on which the instance of SQL Server is running
SYSDATETIME ()-Returns a datetime2(7) value that contains the date and time of the computer on
which the instance of SQL Server is running. The time zone offset is not included.
SQL Server 2019 Page: 19 SQL and T-SQL
ARITHMETIC OPERATIONS on data & time data type “+”, “-“ are the operations which can be used
for performing operations on date type data.
DATE + NUMBER = DATE
DATE – NUMBER = DATE
DATE – DATE = NUMBER [Number of days]
SELECT HIREDATE, HIREDATE+15, HIREDATE-28 FROM EMP
DAY (DATE) -------- extracts days from date
MONTH (DATE) ----- extracts months from date
YEAR (DATE) ------ extracts year from date
SELECT DAY(GETDATE())
SELECT MONTH(GETDATE())
SELECT YEAR(GETDATE())
DATEADD(DATEPART , NUMBER , DATE) - It is used to add number of days, months, years to a
given date.
DATEPART can be specified with this format - DD: MM: YY: HH: MI: SS: DW
SELECT DATEADD(DAY,10,GETDATE())
SELECT DATEADD(DD,10,GETDATE())
SELECT DATEADD(MONTH,10,GETDATE())
SELECT DATEADD(MM,10,GETDATE())
SELECT DATEADD(YEARS,10,GETDATE())
SELECT DATEADD(YY,10,GETDATE())
DATEDIFF( DATEPART, STARTDATE, ENDDATE) - It returns difference between 2 dates in
terms of days, months & years.
SELECT ENAME, DATEDIFF(DD,HIREDATE,GETDATE()) DAYS FROM EMP
DATEPART(DATEPART,DATE)- It extracts individual parts of a table.
DATEPART(DD,GETDATE()) – MM: YY: HH: MI: SS: DW
DATENAME(DATEPART,DATE) - In this function month name, day name will be extracted other
date parts providing same output.
DATENAME(MM,GETDATE()) ---- JUNE(Based on the current server date)
DATENAME(DW,GETDATE()) ---- MON
EOMONTH(<date>)—it will give end day of month
SYSDATETIMEOFFSET() - Returns a datetimeoffset(7) value that contains the date and time of the computer
on which the instance of SQL Server is running. The time zone offset is included.
SYSUTCDATETIME() - Returns a datetime2 value that contains the date and time of the computer on which
the instance of SQL Server is running. The date and time is returned as UTC time (Coordinated Universal Time).
The fractional second precision specification has a range from 1 to 7 digits. The default precision is 7 digits.
DATEFROMPARTS - This function returns a date value that maps to the specified year, month, and day values.
DATETIME2FROMPARTS - This function returns a datetime2 value for the specified date and time arguments.
The returned value has a precision specified by the precision argument.
DATETIMEFROMPARTS - This function returns a datetime value for the specified date and time arguments.
DATETIMEOFFSETFROMPARTS - Returns a datetimeoffset value for the specified date and time arguments.
The returned value has a precision specified by the precision argument, and an offset as specified by the offset
arguments.
SMALLDATETIMEFROMPARTS - Returns a smalldatetime value for the specified date and time.
TIMEFROMPARTS - Returns a time value for the specified time and with the specified precision.
SWITCHOFFSET - Returns a datetimeoffset value that is changed from the stored time zone offset to a
specified new time zone offset.
TODATETIMEOFFSET - Returns a datetimeoffset value that is translated from a datetime2 expression.
Q) Display all those Employees data that have been hired on Sunday.
SELECT ENAME, HIREDATE FROM EMP WHERE DATENAME(DW,HIREDATE) = 'SUNDAY'
Q) Display all those Employees who have been hired in the month of December.
SELECT ENAME,HIREDATE FROM EMP WHERE DATENAME(MM,HIREDATE)= 'DECEMBER'
SQL Server 2019 Page: 20 SQL and T-SQL
Q) Display all those Employees who have been hired in second half of the week.
SELECT ENAME, HIREDATE FROM EMP
WHERE DATEPART (DW, HIREDATE) > = ROUND(7/2.0,0)
DATA CONVERSION:
CAST - These functions convert an expression of one data type to another.
CONVERT - These functions convert an expression of one data type to another.
PARSE - Returns the result of an expression, translated to the requested data type in SQL Server.
TRY_CAST - Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
TRY_CONVERT - Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
TRY_PARSE - Returns the result of an expression, translated to the requested data type, or null if the cast fails
in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
This function will support to convert the data stored with one type to the other type.
SQL SERVER will convert the data with the support of following two functions.
CAST(SOURCE_DATA AS TARGET_DATA_TYPE)
TRY_CAST ( expression AS data_type [ ( length ) ] )
SET DATEFORMAT dmy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
SET DATEFORMAT mdy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
CONVERT(TARGET_DATA_TYPE, SOURCE_DATA [NUMBER])
SELECT ENAME + ' WORKING AS ' + JOB + ' IN DEPT ' + CAST(DEPTNO AS
VARCHAR(3)) FROM EMP
** String and String can only be concatenated.
** String and Integer cannot be concatenated.
SELECT 5/ CAST(2 AS FLOAT)
SELECT 5/ CONVERT(FLOAT,2)
SELECT CONVERT(VARCHAR(30), GETDATE(),0)
SELECT CONVERT(VARCHAR(30), GETDATE(),8) for time
** 0 stands for Date formats, there are more than 100 Date formats.
** 8 & 108 are particularly assigned for time format
TRY_CONVERT (data_type [ ( length ) ], expression [, style ] )
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
select TRY_CONVERT(int,'12345')
FORMAT (value, format [, culture ])
Returns a value formatted with the specified format and optional culture in SQL Server 2017. Use the FORMAT
function for locale-aware formatting of date/time and number values as strings
SELECT FORMAT(getdate(), 'dd/MM/yyyy', 'en-US' )
SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS Result;
SELECT PARSE('€345,98' AS money USING 'de-DE') AS Result;
SET LANGUAGE 'English';
SELECT PARSE('12/16/2010' AS datetime2) AS Result;
Select TRY_PARSE ( string_value AS data_type [ USING culture ] )
SELECT NULLIF(‘X’,’Y’)--- X
SELECT ENAME,LEN(ENAME)L1,JOB,LEN(JOB)L2 NULLIF(LEN(ENAME),LEN(JOB))RES
FROM EMP
IIF ( boolean_expression, true_value, false_value )
Returns one of two values, depending on whether the Boolean expression evaluates to true or false in SQL
Server.
SELECT IIF(1=1,'TRUE','FALSE')
CHOOSE (index, val_1, val_2 [, val_n ] )
Returns the item at the specified index from a list of values in SQL Server.
SELECT CHOOSE ( 1,'ONE','TWO','THREE')
Cursor Functions
@@CURSOR_ROWS - This returns the number of qualifying rows currently in the last cursor opened on the
connection. To improve performance, SQL Server can populate large keyset and static cursors asynchronously.
@@CURSOR_ROWS can be called to determine that the number of the rows that qualify for a cursor are
retrieved at the time of the @@CURSOR_ROWS call.
-m The cursor populates asynchronously. The value returned (-m) is the number of rows
currently in the keyset.
-1 The cursor is dynamic. Because dynamic cursors reflect all changes, the number of rows that
qualify for the cursor constantly changes. The cursor does not necessarily retrieve all qualified rows.
SQL Server 2019 Page: 23 SQL and T-SQL
0 No cursors have been opened, no rows qualified for the last opened cursor, or the last-
opened cursor is closed or deallocated.
n The cursor is fully populated. The value returned (n) is the total number of rows in the cursor.
CURSOR_STATUS - For a given parameter, CURSOR_STATUS shows whether or not a cursor declaration has
returned a cursor and result set.
@@FETCH_STATUS - This function returns the status of the last cursor FETCH statement issued against any
cursor currently opened by the connection.
0 The FETCH statement was successful.
-1 The FETCH statement failed or the row was beyond the result set.
-2 The row fetched is missing.
-9 The cursor is not performing a fetch operation.
Metadata Functions:
@@PROCID - Returns the object identifier (ID) of the current Transact-SQL module. A Transact-SQL module can
be a stored procedure, user-defined function, or trigger. @@PROCID cannot be specified in CLR modules or
the in-process data access provider.
INDEX_COL - Returns the indexed column name. Returns NULL for XML indexes.
APP_NAME - This function returns the application name for the current session, if the application sets that
name value.
INDEXKEY_PROPERTY - Returns information about the index key. Returns NULL for XML indexes.
APPLOCK_MODE - This function returns the lock mode held by the lock owner on a particular application
resource. As an application lock function, APPLOCK_MODE operates on the current database. The database is
the scope of the application locks.
INDEXPROPERTY - Returns the named index or statistics property value of a specified table identification
number, index or statistics name, and property name. Returns NULL for XML indexes.
APPLOCK_TEST - This function returns information as to whether or not a lock can be granted on a particular
application resource, for a specified lock owner, without acquisition of the lock. As an application lock
function, APPLOCK_TEST operates on the current database. The database is the scope of the application locks.
NEXT VALUE FOR - Generates a sequence number from the specified sequence object.
ASSEMBLYPROPERTY - This function returns information about a property of an assembly.
OBJECT_DEFINITION - Returns the Transact-SQL source text of the definition of a specified object.
COL_LENGTH - This function returns the defined length of a column, in bytes.
OBJECT_ID - Returns the database object identification number of a schema-scoped object.
COL_NAME - This function returns the name of a table column, based on the table identification number and
column identification number values of that table column.
OBJECT_NAME - Returns the database object name for schema-scoped objects. For a list of schema-scoped
objects
COLUMNPROPERTY - This function returns column or parameter information
OBJECT_SCHEMA_NAME - Returns the database schema name for schema-scoped objects. For a list of schema-
scoped objects
DATABASE_PRINCIPAL_ID - This function returns the ID number of a principal in the current database
OBJECTPROPERTY - Returns information about schema-scoped objects in the current database. For a list of
schema-scoped objects
DATABASEPROPERTYEX - For a specified database in SQL Server, this function returns the current setting of the
specified database option or property.
OBJECTPROPERTYEX - Returns information about schema-scoped objects in the current database. For a list of
these objects
DB_ID - This function returns the database identification (ID) number of a specified database.
SQL Server 2019 Page: 24 SQL and T-SQL
ORIGINAL_DB_NAME - Returns the database name specified by the user in the database connection string. This
database is specified by using the sqlcmd-d option (USE database). It can also be specified with the Open
Database Connectivity (ODBC) data source expression (initial catalog =databasename).
DB_NAME - This function returns the name of a specified database.
PARSENAME - Returns the specified part of an object name. The parts of an object that can be retrieved are the
object name, owner name, database name, and server name.
FILE_ID - For the given logical name for a component file of the current database, this function
returns the file identification (ID) number
SCHEMA_ID - Returns the schema ID associated with a schema name.
FILE_IDEX - This function returns the file identification (ID) number for the specified logical name of a data,
log, or full-text file of the current database.
SCHEMA_NAME - Returns the schema name associated with a schema ID.
FILE_NAME - This function returns the logical file name for a given file identification (ID) number.
SCOPE_IDENTITY - Returns the last identity value inserted into an identity column in the same scope. A scope
is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same
stored procedure, function, or batch, they are in the same scope.
FILEGROUP_ID - This function returns the filegroup identification (ID) number for a specified filegroup name.
SERVERPROPERTY - Returns property information about the server instance.
FILEGROUP_NAME - This function returns the filegroup name for the specified filegroup identification (ID)
number.
STATS_DATE - Returns the date of the most recent update for statistics on a table or indexed view.
FILEGROUPPROPERTY - This function returns the filegroup property value for a specified name and filegroup
value.
TYPE_ID - Returns the ID for a specified data type name.
FILEPROPERTY - Returns the specified file name property value when a file name in the current database and a
property name are specified. Returns NULL for files that are not in the current database.
TYPE_NAME - Returns the unqualified type name of a specified type ID.
FULLTEXTCATALOGPROPERTY - Returns information about full-text catalog properties in SQL Server 2019 (15.x).
TYPEPROPERTY - Returns information about a data type.
FULLTEXTSERVICEPROPERTY - Returns information related to the properties of the Full-Text Engine. These
properties can be set and retrieved by using sp_fulltext_service.
VERSION - Returns the version of SQL Data Warehouse or Parallel Data Warehouse running on the appliance.
JSON Functions:
Use the functions described on the pages in this section to validate or change JSON text or to extract
simple or complex values.
ISJSON -Tests whether a string contains valid JSON.
JSON_VALUE - Extracts a scalar value from a JSON string.
JSON_QUERY - Extracts an object or an array from a JSON string.
JSON_MODIFY - Updates the value of a property in a JSON string and returns the updated JSON string.
Configuration Functions:
These scalar functions return information about current configuration option settings
@@DATEFIRST - This function returns the current value of SET DATEFIRST, for a specific session.
@@OPTIONS - Returns information about the current SET options.
@@DBTS - This function returns the value of the current timestamp data type for the current database.The
current database will have a guaranteed unique timestamp value.
@@REMSERVER (deprecated) - Returns the name of the remote SQL Server database server as it appears in the
login record.
@@LANGID - Returns the local language identifier (ID) of the language that is currently being used.
@@SERVERNAME - Returns the name of the local server that is running SQL Server
SQL Server 2019 Page: 25 SQL and T-SQL
M2:
CASE
WHEN Boolean_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
Q) Display ENAME, SAL and INCREMENT the salary with difference %’s based on category of JOB.
Manager – 18%, Clerk – 15%, Others – 12%
SELECT ENAME,SAL,JOB,
CASE JOB
WHEN 'MANAGER' THEN SAL*18/100
WHEN 'CLERK' THEN SAL * 15/100
ELSE
SAL*12/100
END INCR
FROM EMP
Q) Display ENAME, DEPTNO, SAL and INCREMENT the Salary with different %’s on category of Dept
No 10 – 20%, Dept no 20 – 18%, Dept no 30 – 15%
SELECT ENAME, DEPTNO, SAL,
CASE DEPTNO
WHEN 10 THEN SAL* 20/100
WHEN 20 THEN SAL * 18/100
WHEN 30 THEN SAL*15/100
END INCR
FROM EMP
Using Case statement in order by clause
select * from emp
order by case DEPTNO
when 10 then EMPNO
SQL Server 2019 Page: 26 SQL and T-SQL
UNION
SELECT JOB FROM EMP WHERE DEPT NO=10
** INTERSECT & EXCEPT called as a semi joins
JOINS
Logical Joins
It is a process of joining columns from 2 or more tables, which always produces a new table
Joining conditions is must
To join n tables n-1 join conditions are required
A joining condition is followed by any number of filtering conditions.
Non-ANSI Joins (With Operators)
Inner Join (=)
Left Join (*=)
Right Join (=*)
Cross Join (,)
ANSI Joins (with Key words)
Inner Join
Equi join(=)
Non Equi (Other then =)
Outer Joins
Left Join
Right Join
Outer Join
Cross Join
Physical joins
Nested Loop joins
Merge Joins
Hash Joins
Non-ANSI joins (These are implemented through operators)
Inner Join (Equi join, Non Equi Join)
Outer Join (Left Outer Join, Right Outer Join, Cartesian Join, Self-Join)
ANSI Joins (These are implemented through key words)
Inner Join or Join, Cross join
Outer Joins (Left Outer Join, Right Outer Join, Full Outer Join)
NON ANSI JOINS - INNER JOIN
EQUI JOIN:
This Join concept supports to join the columns from two or more tables by making a joining
condition using “equal to” operator.
To work with equi join tables should contain at least one common column with respect to
data and data type.
If tables are containing common column names, to use them in a query they should be
preceded by table name or table alias name.
TABLE ALIAS:
Table Alias can be used under any clause.
It is other name provided for a table.
It can be specified with or without as keyword.
It is a temporary name provided for a table, which provides its usage till the query is in
execution.
SQL Server 2019 Page: 30 SQL and T-SQL
It is flexible in usage.
It can be used anywhere in SELECT statement.
SELECT EMPNO, ENAME, JOB, SAL, E.DEPTNO, DNAME, LOC
FROM EMP, DEPT WHERE DEPTNO = DEPTNO
SQL Server 2005 is restricted with the implementation of Outer joins through operator
In order to implement outer joins in SQL Server 2005 data base compatibility level should be
used by a predefined procedure called SP_DBCMPTLEVEL.
Syntax :
SP_DBCMPTLEVEL @DBNAME = <'DATABASE_NAME'>
@NEW_CMPTLEVEL = '80'
For SQL SERVER Version 7.00 = 70 should be used
For SQL SERVER Version 2000 = 80 should be used
For SQL SERVER Version 2005 = 90 should be used
SQL Server supports two types of Outer Joins through NON ANSI JOINS
LEFT OUTER JOIN: At this joining concept, Outer Join operator is placed on left side of joining
condition, it will extract matched and unmatched rows from the table which is placed on LEFT side of
Joining condition and substitutes NULL Values for the columns of a table which is on RIGHT side of
the Joining Condition.
Syntax:
SELECT * FROM TABLE1 , TABLE2
WHERE TABLE1.COLUMN1 *= TABLE2.COLUMN2
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE E.DEPTNO *= D.DEPTNO
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE D.DEPTNO *= E.DEPTNO
RIGHT OUTER JOIN: At this joining concept, Outer Join operator is placed on RIGHT side of joining
condition, it will extract matched and unmatched rows from the table which is placed on RIGHT side
of Joining condition and substitutes NULL Values for the columns of a table which is on LEFT side of
the Joining Condition.
Syntax:
SELECT * FROM TABLE1 , TABLE2
WHERE TABLE1.COLUMN1 =* TABLE2.COLUMN2
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE E.DEPTNO =* D.DEPTNO
SELECT EMPNO, ENAME, JOB, SAL, D.DNAME
FROM EMP E , DEP D WHERE D.DEPTNO =* E.DEPTNO
ANSI JOINS: This are implemented by using key words used at FROM Clause of SELECT STATEMENT.
SELECT TABLE1.COLUMN1,TABLE2.COLUMN2
FROM TABLE1 [ALIAS] < JOIN_TYPE > TABLE2 [ALIAS]
ON <JOIN_TYPE> -- JOINING CONDITION
TABLE3[ALIAS] ON ---- JOINING CONDITION
INNER JOIN OR JOIN: A join that displays only the rows that have a match in both joined tables
EQUI JOIN
SELECT E.*,D.* FROM EMP E INNER JOIN DEPT D ON E.DEPTNO = D.DEPTNO
NON EQUI JOIN :
SELECT E.*, S.* FROM EMP E INNER JOIN SALGRADE S
ON SAL BETWEEN LOSAL AND HISAL
EQUI & NON EQUI JOIN:
SELECT E.*, D.*, S.* FROM EMP E INNER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO INNER JOIN SALGRADE S
ON E.SAL BETWEEN S.LOSAL AND S.HISAL
SELF JOIN:
SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME FROM EMP E INNER JOIN EMP M
ON E.EMPNO = M.MGR
CROSS JOIN: Cartesian product of two tables
SELECT EMP.*, DEPT.* FROM EMP CROSS JOIN DEPT
SELECT EMP.*, DEPT.*, SALGRADE.*
FROM EMP CROSS JOIN DEPT CROSS JOIN SALGRADE
OUTER JOINS
SQL Server 2019 Page: 32 SQL and T-SQL
LEFT OUTER JOIN: A join that displays all the rows from left table matched rows from the right table
SELECT E.*, D.* FROM EMP E LEFT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
RIGHT OUTER JOIN: A join that displays all the rows from right table matched rows from the left table
SELECT E.*, D.* FROM EMP E RIGHT OUTER JOIN DEPT D
ON E.DEPTNO = D.DEPTNO
FULL OUTER JOIN: It is a combination of LEFT and RIGHT Outer joins.
We can use functions in Joins
Joining more than two tables
Select a.*, b.*, c.* from EMP
Inn join dept b on a.deptno=b.deptno
Inner join salgrade c on a.sal between c.lowsal and c.highsal
Using Query result in joins as tables
Select a.*, b.*, c.* from EMP
Inn join (select * from dept) b on a.deptno=b.deptno
Inner join salgrade c on a.sal between c.lowsal and c.highsal
Physical joins
These are the joins that users don’t use/write in their SQL queries. Instead these are implemented inside
SQL Server engine as operators or algorithms to implement the Logical Joins. Their types are Nested Loop,
Merge and Hash.
Nested Loop joins
Merge Joins
Hash Joins
A Query which allows to write other query is called Outer Query or Main Query.
A Query which is written in main query is called INNER or SUB-QUERY
NESTED Query always gets executed in the following ways
First Executes INNER QUERY
Then Executes OUTER QUERY
**SQL Server supports to write 32 Sub Queries where as in ORACLE it supports up to 255 Sub
Queries.
CLASSIFICATION OF SUB QUERIES
Based on Usage
Normal Sub Query
Co-related Sub Query
Based on Execution
Single Column – Single Row
Single Column – Multiple Rows
Multiple Columns – Single Rows (SQL Server Does not supports)
Multiple Columns – Multiple Rows (SQL Server Does not supports)
A SUB-QUERY can be written
At WHERE Clause
At HAVING Clause
At FROM Clause ----- called as INLINE VIEW
As an Expression ---- called as SCALAR SUB QUERY
Under DML Queries
SUB-QUERY AT WHERE CLAUSE
Select as Sub Query can be written at Where Clause of Outer Query.
Output of Sub Query igs never displayed
Output of Sub Query will be given to OUTER Query for Comparison, Based on It OUTER
Query displaces the Output
SELECT * FROM TABLE -- MAIN / OUTER QUERY WHERE EXPRESSION OPERATOR (SELECT
FROM TABLE2 WHERE CONDITION)--INNER/SUBQUERY
Q) Display EMPNO, ENAME, JOB, SAL, DEPTNO of that Employee who is being paid by Max Salary.
SELECT EMPNO, ENAME, JOB, SAL, DEPTNO
FROM EMP WHERE SAL = ( SELECT MAX(SAL) FROM EMP)
**Single row and Single Column.
Q) Display EMPNO, ENAME, JOB, SAL of those Employees whose salary is more than Average Salary
of all Employees.
SELECT EMPNO, ENAME, JOB, SAL
FROM EMP WHERE SAL > ( SELECT AVG (SAL) FROM EMP)
Q) Display Ename, Job of those Employees who are working on a same job as of TURNER.
SELECT ENAME, JOB
FROM EMP WHERE JOB = ( SELECT JOB FROM EMP WHERE ENAME = 'TURNER')
Q) Display ENAME,SAL of those Employees whose salary is more than average salary of Deptno 20.
SELECT ENAME , SAL
FROM EMP WHERE SAL > ( SELECT AVG(SAL) FROM EMP WHERE DEPTNO = 20)
Q) Display ENAME,JOB,SAL of those Employees who are working on a same job as of “Allen” and
Salary is more than Salary of “Miller”.
SELECT ENAME, JOB, SAL
FROM EMP WHERE JOB = ( SELECT JOB FROM WHERE ENAME = 'ALLEN')
AND SAL > ( SELECT SAL FROM EMP WHERE ENAME = 'MILLER')
Q) Display Second Max Salary.
SELECT MAX(SAL) FROM EMP WHERE SAL < ( SELECT MAX(SAL) FROM EMP)
SELECT ENAME, EMPNO, JOB, SAL , DEPTNO FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
SQL Server 2019 Page: 34 SQL and T-SQL
In order to store explicit values for IDENTITY COLUMN Following SET Command should be
used.
SET IDENTITY_INSERT < TABLE_NAME > ON / OFF [ DEFAULT IS OFF ]
When Explicit Values are provided for identity Colum it is must to mention that column name
in the Column List.
IDENTITY COLUMN will allows duplicates.
When Explicit Values are stored in IDENTITY COLUMN, later when implicit values are stored
it would be generate the sequence of numbers based on the biggest value of that column.
IDENTITY COLUMN can be associated with the following data types i.e
INT, BIGINT, SMALLINT, TINYINT, DECIMAL OR NUMERIC with SCALE
@@IDENTITY - It returns the Last Value stored into IDENTITY COLUMN (Related to Last Table)
It works at session level.
SCOPE_IDENTITY - It returns the Last Value stored into IDENTITY COLUMN.
SELECT SCOPE_IDENTITY ()
IDENT_CURRENT - This function returns the last IDENTITY COLUMN value which is stores in a
specific table.
SELECT IDENT_CURRENT( < TABLE_NAME > )
SYS.IDENTITY_COLUMNS - This System Table also supports to get the last value of IDENTITY
COLUMN of any table.
SELECT LAST_VALUE FROM SYS.IDENTITY_COLUMNS
WHERE [OBJECT_ID] = OBJECT_ID( < TABLE_NAME > )
IDENT_SEED ( < TABLE_NAME > ) - It returns the start value of the IDENTITY COLUMN
created at table.
SELECT IDENT_SEED ('PRODUCT')
IDENT_INCR ( < TABLE_NAME > ) - It returns the incremented value of the IDENTITY
COLUMN created at table.
SELECT IDENT_INCR ('PRODUCT')
To restart the sequence of Numbers for IDENTITY COLUMN an option called CHECKIDENT of DBCC (
DATABASE CONSISTENCY CHECKER ) Command.
DBCC CHECKIDENT ( <TABLE_NAME>, RESEED , VALUE )
Example:
CREATE TABLE PRODUCT ( SNO INT IDENTITY, PCODE INT, PNAME VARCHAR(10),
QTY INT, PRICE FLOAT, AMT AS (QTY * PRICE) )
INSERT INTO PRODUCT VALUES (201,'X',10,15)
INSERT INTO PRODUCT VALUES (202,'Y',10,15)
INSERT INTO PRODUCT VALUES (203,'Z',10,15)
INSERT INTO PRODUCT VALUES (204,'A',10,15)
INSERT INTO PRODUCT VALUES (204,'B',10,15)
SET IDENTITY_INSERT PRODUCT ON
INSERT INTO PRODUCT (SNO,PCODE,PNAME,QTY,PRICE)
VALUES (6,205,'C',10,15)
SELECT @@IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('PRODUCT')
SELECT LAST_VALUE FROM SYS.IDENTITY_COLUMNS
WHERE [OBJECT_ID] = OBJECT_ID('PRODUCT')
DBCC CHECKIDENT('PRODUCT',RESEED,3)
Q) Create a Table Called STUDENT which contains ROLLNO, NAME, MPC MARKS.
Calculate for total and average marks.
Sequence
CREATE SEQUENCE [schema].[Name_of_Sequence]
[ AS <data type> ]
[ START WITH <value> ]
[ INCREMENT BY <value> ]
SQL Server 2019 Page: 40 SQL and T-SQL
SAVE TRAN F
INSERT DEPT VALUES (.....)
UPDATE DEPT SET COL = VAL WHERE DEPTNO = 10
SAVE TRAN S
DELETE FROM SALGRADE
DELETE FROM EMP
Three Scenarios for above example.
First Second Third
ROLLBACK TRAN S ROLLBANK TRAN F
ROLLBACK TRAN F ROLLBACK
ROLLBACK
When a session contains a transaction it cannot be closed directly , if it is trying closed it confirms for
COMMIT and ROLLBACK of Transactions.
DATABASE CONSTRAINTS:
Constraints refers to rules or conditions
Data Constraint will make SQL Server to avoid invalid data entry.
Every Constraint is provided by a unique name, which can be of predefined or user defined.
To specify User Defined Constraint Name a Keyword called CONSTRAINT is used.
Advantage of Constraint Name is found when a constraint is disabled/enabled or when the
constraint is dropped.
Constraint is created as DATABASE Object.
Constraint Names should be always provided with unique names Because it will be checked
at Schema Level.
Types of Constraints
DOMAIN INTEGRITY CONSTRAINTS -- NOTNULL, CHECK, DEFAULT
ENTITY INTEGRITY CONSTRAINTS -- PRIMARY KEY, UNIQUE
REFERENTIAL INTEGRITY CONSTRAINTS -- FOREIGN KEY
DOMAIN INTEGRITY CONSTRAINT
These constraints are specified immediately after a Column, It includes NOTNULL, CHECK, DEFAULT.
NOTNULL
It is not a Constraint.
It can be provided for any Number of Columns.
It will not allow to store NULL VALUES, But will allow to store Duplicates
CHECK
This Constraint is used to specify User Defined Conditions
Any Number of Columns Can be set with the CHECK Constraint
DEFAULT
This Constraint is used to specify Default Value for Column.
When a user does not provide data (INSERT) then it will store Default value.
Example:
CREATE TABLE EMP1(
ENO INT NOT NULL, ENAME VARCHAR(10) NOT NULL,
JOB VARCHAR(15) CHECK (JOB IN ('CLERK','MANAGER','OPERATIONS')),
SAL INT CONSTRAINT SAL_CHK CHECK (SAL BETWEEN 15000 AND 20000),
DOJ SMALLDATETIME DEFAULT GETDATE(),
DNO INT CONSTRAINT DF_DNO DEFAULT 20)
ENTITY INTEGRITY CONSTRAINT
These Constraints can be specified in two levels.
Column Level – Immediately after a Column.
Table / Entity Level – after all the columns
It Includes PRIMARY KEY, UNIQUE CONSTRAINTS
SQL Server 2019 Page: 47 SQL and T-SQL
UNIQUE
This Constraint will not allow to store duplicate values but can store only ONE NULL Value.
It Can be used for any number of times
COLUMN LEVEL
CREATE TABLE STUDENT
(RNO INT UNIQUE, SN VARCHAR(10) CONSTRAINT SN_UQ UNIQUE)
TABLE / ENTITY LEVEL
CREATE TABLE STUDENT
(RNO INT , SN VARCHAR(10),UNIQUE(RNO) CONSTRAINT SN_UQ UNIQUE(SN))
COMPOSITE UNIQUE KEY
Multiple Columns set with One UNIQUE Constraint is called Composite Unique Key.
It is created only at Entity Level or Table Level.
Composite Unique will allow to store one column with duplicates only when corresponding
Column contains Unique Data
Minimum of two Columns and Maximum of 16 Columns.
Example:
CREATE TABLE STUDENT(
RNO INT, SNAME VARCHAR(10), CLASS INT, UNIQUE (RNO,CLASS))
PRIMARY KEY: { NOT NULL + UNIQUE }
Which means it will not allow NULL values and duplicates.
A table can have only one Primary Key which can be created at Table or Column Level.
COLUMN LEVEL
CREATE TABLE STUDENT ( RNO INT PRIMARY KEY, SNAME VARCHAR(10))
TABLE LEVEL
CREATE TABLE STUDENT ( RNO INT , SNAME VARCHAR(10) PRIMARY KEY (RNO))
COMPOSITE PRIMARY KEY
Multiple Columns set with One Primary key refers to Composite Primary Key.
It can be created only at table level.
Behavior of Composite Primary Key that it will allow One column Store Duplicates only
when the corresponding column contains Unique Data.
Composite Primary Key can be created Minimum of 2 and Maximum of 16 Columns
**Difference in Composite Unique Key and Composite Primary Key – Composite Unique Key will
allow NULL Values, Composite Primary Key will not allow NULL Values.
CREATE TABLE STUDENT (
RNO INT, SNAME VARCHAR(10), CLASS INT, PRIMARY KEY (RNO, CLASS))
CREATING MULTIPLE CONSTRAINTS ON A SINGLE COLUMN
CREATE TABLE EMPLOYEE (
ENO INT PRIMARY KEY,
ENAME VARCHAR(15) NOT NULL UNIQUE,
SAL INT NOT NULL UNIQUE CHECK (SAL BETWEEN 15000 AND 20000))
REFEREINTAL INTEGRITY CONSTRAINT
This Constraint is used to create relationships among tables.
It supports to create following relationships.
ONE to ONE and ONE to MANY { DIRECT IMPLEMENTATION }
MANY to MANY { INDIRECT IMPLEMENTATION }
FOREIGN KEY
It will allow to store valid values that are present in another Column.
Foreign Key Column Name and the Column where the data is been checked can be with
same name are different names.
If column names are different it is must that the Data Types and Data Size should be same.
When Foreign Key Column data gets referred to another column, on that column there
should be either a PRIMARY KEY or a UNIQUE Constraint.
SQL Server 2019 Page: 48 SQL and T-SQL
To satisfy the First Normal Form, for the above un-normalized table, the below tables can be created
to normalize the tables.
Customer
CID(Primary Key) Cname Caddr Cphone
Order 1
OrderNo(Primary Key) Ord_Date items CID(Foregin Key)
Order 2
OrderNo Ord_date ItemNo Itemname Qty Cid(Forign key)
Items
ItemNo Itemname Qty OrderNo(Foreign Key)
SQL Server 2019 Page: 50 SQL and T-SQL
Syntax:
CREATE [UNIQUE] / [CLUSTERED] / [NON CLUSTERED]
ON [ TABLE_NAME (COLUMN_NAME…..)]
**When index is created on multiple columns it is called as Composite Index.
CLUSTERED INDEX
It will Alter the physical representation of rows in a table.
A table can have only One Clustered Index.
It will always arrange the data of a table in Ascending order
Data pages and Index pages will be stored at one level.
Index should be created for a column where more than one search value is available.
CREATE CLUSTERED INDEX INDX1 ON EMP( EMPNO )
NON CLUSTERED INDEX
This index will not Alter the physical requirement of rows in a table.
A table can have 249 Non Clustered Index’s.
Data is not arranged in Order.
It is a default index created.
Data pages & index pages are stored at different level.
CREATE NONCLUSTERED INDEX INDX2 ON EMP(ENAME)
CREATE NONCLUSTERED INDEX INDX3 ON EMP(JOB)
UNIQUE INDEX
This index can be created only on those columns which contains unique data.
This index is automatically created when unique constraint is created on a column.
CREATE UNIQUE INDEX INDX4 ON DEPT(DEPTNO)
Column store INDEX
A columnstore index is a technology for storing, retrieving, and managing data by using a columnar
data format, called a columnstore
CREATE COLUMNSTORE INDEX CSIX_EMP_EMPNO on EMP(EMPNO)
Filter Index
CREATE NONCLUSTERED INDEX INDX2 ON EMP(deptno) where deptno=10
SP_REFRESHVIEW V1
Example:
CREATE VIEW V2
AS
SELECT TOP(5) EMPNO, ENAME, SAL, DEPTNO, FROM EMP ORDER BY SAL
** For ORDER BY Clause TOP keyword is must.
CREATE VIEW V3
AS
SELECT EMPNO, ENAME, DEPTNO FROM EMP WHERE DEPTNO = 10
INSERT V3 VALUES()
Check Option View: When this option is associated with a view then it will check the condition
specified at where clause before data is inserted or updated into base object.
CREATE VIEW V4
AS
SELECT EMPNO, ENAME FROM EMP WHERE DEPTNO = 10 WITH CHECK OPTION
Complex View: A view is said to be complex view when it is associated with any of the following
Group By Clause
Group Functions
Distinct Operator
Joins
Mathematical Expressions
By Default Complex View is not updatable view(i.e. read only)
CREATE VIEW V5
AS
SELECT DEPTNO, SUM(SAL) TOTSAL FROM EMP GROUP BY DEPTNO
CREATE VIEW V6
AS
SELECT DISTINCT DEPTNO FROM EMP
CREATE VIEW V7
AS
SELECT ENAME, JOB, SAL, SAL*12 FROM EMP
CREATE VIEW V8
AS
SELECT EMPNO, ENAME, JOB, DNAME, LOC FROM EMP, DEPTNO
WHERE EMP.DEPTNO = DEPT.DEPTNO
To display the Query stored in view SP_HELPTEXT < VIEW_NAME >
To display the metadata of a view SP_HELP < VIEW_NAME >
To display list of views that are dependent on a table
SP_DEPENDS < TABLE_NAME > / < VIEW_NAME >
List of columns, table names that are enclosed in view through SELECT Query
Encrypted View:
When a view is encrypted it does not support to display the text which is stored in a view.
SQL Server does not support decryption of view.
To create this view, it should be associated by with encryption
The query which is stored in encrypted view can be altered
CREATE VIEW V9 WITH ENCRYPTION
AS
SELECT * FROM EMP
Schema Binding View: Rules to be followed for creating schema binding view.
Schema binding view will not support to store select query with * Selection operator.
It is must that table name specified in select query should be preceded by schema name
The advantage of creating schema binding views is that it will restrict the dropping of the
base objects
CREATE VIEW V10 WITH SCHEMA BINDING
SQL Server 2019 Page: 55 SQL and T-SQL
AS
SELECT * FROM EMP
DROP TABLE DEPT --- ERROR
Indexed View:
These views will provide the improved performance than standard views.
These views when gets created should be attached with schema binding and there should be
an existing of clustered index.
These views will provide their importance specially when a query contains aggregate functions
If a query contains aggregate function it includes following steps for the execution of a query.
SELECT DEPT NO, COUNT (*) FROM EMP GROUP BY DEPTNO
1) Checks the syntax
2) Compiles the query
3) Execution plan is generated
4) Query gets executed
i. Takes the rows of database into buffer
ii. Sorts the data
iii. Creates a group on each deptno
iv. Count function will visit to each group to count the number of employees
v. Displays the output
vi. All these steps are avoided by creating indexed views.
COMMON TABLE EXPRESSIONS
It is often called as temporary view.
It will create an object to store query at session level i.e. it provides its usage at all the
queries that are connected to Common Table Expressions.
Table alias column aliases specified in Common Table Expressions should be used at
immediate query which works on that table.
It does not allow using original columns and original table name.
Common Table Expressions will support to write a query in 2 ways
Non recursive
Recursive
At non recursive query, Common Table Expression will contain a select query on some object and it
gets referred by the other name through a query which provides its execution
Syntax:
WITH TABLE_ALIAS (COLUMN_ALIAS)
AS
( SELECT QUERY) [ SELECT / INSERT / UPDATE / DELETE ]
If non recursive query is enclosed with multiple tables, mathematical expressions, distinct operator
etc is restricted with Data Manipulation Language Operations
WITH E (ENO, EM, PAY, DN)
AS
(SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP)
SELECT ENO, EM, PAY, DN FROM E
WHERE PAY = (SELECT MAX (PAY) FROM E)
UNION ALL
SELECT * FROM E
SELECT E (EMPNO, EN, PAY, DNO)
AS
(SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP)
INSERT E VALUES (1001,’X’, 1000, 10)
SELECT E (EMPNO, EN, PAY, DNO)
AS
(SELECT EMPNO, ENAME, SAL, DEPTNO FROM EMP)
DELETE FROM E WHERE DN = 10
SQL Server 2019 Page: 56 SQL and T-SQL
Ex2:
select * from
(
select deptno,empno from emp
) [data]
Pivot
(
count(empno) for deptno in ([10],[20],[30])
)
Result
EX3
select * from
(
select b.CalendarYear,a.SalesAmount from AdventureWorksDW2017..FactInternetSales a
Inner join AdventureWorksDW2017..DimDate b on a.OrderDateKey=b.DateKey
)[data]
Pivot
(
sum(SalesAmount) for CalendarYear
in ([2009],[2010],[2011],[2012],[2013],[2014],[2015],[2016])
)
result
Ex4
select * from
(
select d.EnglishCountryRegionName,d.StateProvinceName,
b.CalendarYear,a.SalesAmount from AdventureWorksDW2017..FactInternetSales a
Inner join AdventureWorksDW2017..DimDate b on a.OrderDateKey=b.DateKey
Inner join AdventureWorksDW2017..DimCustomer c on a.CustomerKey=c.CustomerKey
inner join AdventureWorksDW2017..DimGeography d on c.GeographyKey=d.GeographyKey
)[data]
Pivot
(
sum(SalesAmount) for CalendarYear
in ([2009],[2010],[2011],[2012],[2013],[2014],[2015],[2016])
)
SQL Server 2019 Page: 59 SQL and T-SQL
result
Unpivot
)[data]
Pivot
(
sum(SalesAmount) for CalendarYear
in ([2009],[2010],[2011],[2012],[2013],[2014],[2015],[2016])
)
result
select * from
(
select * From #salesPivoted
)[data]
Unpivot
(
salesAmount for Years in
([2009],[2010],[2011],[2012],[2013],[2014],[2015],[2016])
)
Result
TRANSACT – SQL
Transact SQL deals with set of statements that are grouped in the form of a block and submitted at
server at once for execution.
Difference between SQL & TSQL
SQL is a NON PROCEDURAL LANGUAGE since it deals with WHAT data to be extracted.
T-SQL is a PROCEDURAL LANGUAGE, it deals with WHAT Data to be extracted and HOW it
should be displayed.
T-SQL supports to submit a Block to server for execution in two ways.
Anonymous block – it supports to store a block in SQL File.
Stored Block – it stores the blocks in Data Base Server.
Stored Procedures
Stored Functions
Stored Triggers
Global Variables
These variables are comes with software (SQL Server).
These variables can’t be used to initialize the values manually.
These variables will stored with data automatically based on the operations performed by
SQL Server 2019 Page: 60 SQL and T-SQL
SQL Statements.
These variables are preceded by “@@”.
SELECT @@VERSION - returns the version of SQL Server
SELECT @@SERVERNAME - returns the name of the server
SELECT @@SERVICENAME - returns name of the service
SELECT @@ROWCOUNT - returns the number of rows effected by last SQL statement (default is 1)
SELECT @@ERROR - return "0" if there is no error in last executed SQL statement or returns error
number.
To display the List of ERROR messages
SELECT * FROM SYS.MESSAGES
LOCAL VARIABLES (SCALAR VARIABLES or BUFFER VARIABLES)
These variables are created by User.
These variables are provided memory for temporary; hence they are called as BUFFER variable.
These variables will allow storing only one value; hence it is called as SCALAR Variable. If more than
one value stored it gives priority to last value.
These variables should be declared before they are used.
These variables preceded by “@”.
Syntax:
DECLARE @VARIABLE_NAME DATATYPE [( SIZE )]
** In SQL Server 2008 declaration & Initialization can be carried out simultaneously.
DECLARE @VARIABLE_NAME DATATYPE [( SIZE )] [ =VALUE ]
SET: This command is used to set a value for a variable.
SET @VARIABLE = VALUE/EXPRESSION/FUNCTION
PRINT: It is an Output Statement of T-SQL which performs two tasks Display Messages & Display
Memory Values.
PRINT ' MESSAGE ' / @VARIABLE
Q) Write a program to find the addition of two values.
DECLARE @A INT, @B INT, @C INT
SET @A = 70
SET @B = 80
SET @C = @A + @B
PRINT ' SUM OF TWO VALUES '+ CAST(@C AS VARCHAR(4))
Output: “SUM OF TWO VALUES 150”
Q) Write a program to find Division of two values.
DECLARE @A INT, @B INT, @C FLOAT
SET @A = 10
SET @B = 20
SET @C = @A / @B
PRINT 'QUOTIENT FOR TWO VALUES IS '+ CAST(@C AS VARCHAR(5))
Output: “QUOTIENT FOR TWO VALUES IS 0”
DECLARE @A INT, @B INT, @C FLOAT
SET @A = 20
SET @B = 30
SET @C = @A / (CAST(@B AS FLOAT))
PRINT 'QUOTIENT FOR TWO VALUES IS '+ CAST(@C AS VARCHAR(15))
Output: “QUOTIENT FOR TWO VALUES IS 0.66667”
IF CONDITIONAL STATEMENTS
It is used to compare the data provided with the result on Boolean expressions i.e. True or False.
Simple IF
IF Else IF
Nested IF
Simple IF Condition
This conditional statement is used to compare the data and allow to write a single true or
SQL Server 2019 Page: 61 SQL and T-SQL
PRINT 'SEVEN'
GOTO Y
Z:
PRINT 'THANX'
LOOPING CONSTRUCTS
LOOP: Execution of one or more statements repeatedly until a condition is satisfied. SQL Server
supports to work with the following Looping constructs.
WHILE LOOPING CONSTRUCT
WHILE < CONDITION >
BEGIN
< STATEMENTS >
END
Q) Write a program to display first Five Natural Numbers.
DECLARE @I INT
SET @I = 1
WHILE @I<=5
BEGIN
PRINT @I
SET @I = @I+1
END
Q) Write a program to display N Odd Numbers.
DECLARE @N INT,@I INT
SET @N = 10
SET @I = 1
WHILE @I<=@N*2
BEGIN
PRINT @I
SET @I = @I+2
END
Q) Write a program to display reverse of a string without using reverse function.
DECLARE @S VARCHAR(10), @R VARCHAR(10),@L INT
SET @S = 'COMPUTER'
SET @R = SUBSTRING(@S,LEN(@S),1)
SET @L = LEN(@S)-1
WHILE @L>=1
BEGIN
SET @R = @R + SUBSTRING(@S,@L,1)
SET @L = @L-1
END
PRINT 'REVERSE IS ' +@R
Q) Write a program to count number of vowels and consonants in a given string.
DECLARE @S VARCHAR(10),@I INT,@V INT, @C INT
SET @S = 'COMPUTER'
SET @V = 0
SET @C = 0
SET @I = 1
WHILE @I < =LEN(@S)
BEGIN
IF SUBSTRING(@S,@I,1) IN('A','E','I','O','U')
SET @V = @V + 1
ELSE
SET @C = @C + 1
SET @I = @I + 1
END
PRINT 'VOWELS IN THE STRING '+@S+' ARE '+CAST(@V AS VARCHAR(5))
PRINT 'CONSONANTS IN THE STRING '+@S+' ARE '+CAST(@C AS VARCHAR(5))
Q) Write a program to display the given string into substrings eliminating special characters.
DECLARE @W VARCHAR(50),@W1 VARCHAR(50)
SQL Server 2019 Page: 63 SQL and T-SQL
DECLARE @I INT
SET @W='XYZ;ABC;PQR;AAA;BBB'
SET @I=CHARINDEX(';',@W)
WHILE @I>0
BEGIN
SET @W1 = LEFT(@W,@I-1)
IF LEN(@W1)!= 0
PRINT @W1
SET @W = SUBSTRING(@W,@I+1,LEN(@W))
SET @I = CHARINDEX(';',@W)
IF @I = 0
PRINT @W
END
BREAK & CONTINUE:
DECLARE @X INT
SET @X=1
WHILE @X<=10
BEGIN
PRINT @X
IF @X%3=0
BREAK
SET @X=@X+1
END
DECLARE @X INT
SET @X=1
WHILE @X<=10
BEGIN
IF @X%3=0
BEGIN
SET @X=@X+1
CONTINUE
END
PRINT @X
SET @X=@X+1
END
Q) Write a program to check whether a given number is perfect or not.
Perfect Number: Sum of factors of a given number excluding itself should be equal to resultant
number.
N = 4, FACTORS: 1, 2 SUM = 1+2 = 3 {NOT PERFECT}
N = 6, FACTORS: 1, 2, 3 SUM = 1+2+3 = 6 {PERFECT NUMBER}
N=28, FACTORS: 1, 2, 4,7,14 SUM = 1+2+4+7+14 = 28 {PERFECT NUMBER}
DECLARE @N INT, @S INT, @I INT
SET @N = 4
SET @S = 0
SET @I = 1
WHILE @I <= @N/2
BEGIN
IF @N%@I = 0
SET @S = @S + @I
SET @I = @I+1
END
IF @S = @N
PRINT ' IT IS A PERFECT NUMBER '
ELSE
PRINT 'IT IS NOT A PERFECT NUMBER'
EXCEPTION HANDLING:
Errors are classified into 3 types:
Complex Time Errors: These errors are often called as Syntax Errors. These errors are occurred when
SQL Server 2019 Page: 64 SQL and T-SQL
BEGIN CATCH
PRINT 'VALUE DOES NOT EXIST AT PARENT TABLE'
END CATCH
MULTIPLE TRY CATCH BLOCKS
Q) Write a program to Store the run time errors into a table.
CREATE TABLE ERROR_LOG (ERNO INT,ERLI INT,ERMSG VARCHAR(300),ERSEVER INT)
DECLARE @A INT,@B INT,@C INT,@N INT,@S INT
SET @A = 5
SET @B = 0
BEGIN TRY
SET @C = @A/@B
PRINT @C
END TRY
BEGIN CATCH
PRINT 'CANT DIVIDE THE NUMBER BY 0'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
BEGIN TRY
SET @N = -8
SET @S = SQRT(@N)
PRINT @S
END TRY
BEGIN CATCH
PRINT 'CANT FIND THE SQUARE ROOT OF -VE VALUE'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
NESTED TRY CATCH BLOCKS
SET NOCOUNT ON
DECLARE @A INT,@B INT,@C INT,@N INT,@S INT
SET @A = 5
SET @B = 0
BEGIN TRY
SET @C = @A/@B
PRINT @C
BEGIN TRY
SET @N = -8
SET @S = SQRT(@N)
PRINT @S
END TRY
BEGIN CATCH
PRINT 'CANT FIND THE SQUARE ROOT OF -VE VALUE'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
PRINT 'WE ARE OUT OF INNER TRY AND CATCH BLOCK'
END TRY
BEGIN CATCH
PRINT 'CANT DIVIDE THE NUMBER BY 0'
INSERT ERROR_LOG SELECT ERROR_NUMBER(),ERROR_LINE(),
ERROR_MESSAGE(),ERROR_SEVERITY()
END CATCH
Working with EXEC (Execute): This Command is used to execute the queries that are stored in variables.
Syntax: EXEC (VARIABLE)
**The Query stored in a variable can be passed with arguments through variables.
DECLARE @S VARCHAR(200)
SET @S = 'SELECT * FROM EMP'
EXEC (@S)
SQL Server 2019 Page: 67 SQL and T-SQL
DECLARE @S VARCHAR(200)
SET @S = 'SELECT * FROM EMP WHERE DEPTNO =10'
EXEC (@S)
DECLARE @S VARCHAR(200),@DNO INT
SET @DNO = INT
SET @S = 'SELECT * FROM EMP WHERE DEPTNO ='+CAST(@DNO AS VARCHAR(3))
EXEC (@S)
DECLARE @S VARCHAR(200)
SET @S = 'INSERT EMP(EMPNO,ENAME) VALUES(1001,''XYZ'')'
EXEC (@S)
SUB PROGRAMS:
It is a process of splitting a large application program into small modules or blocks.
SQL Server supports to write a sub program based on the following concepts
Stored Procedures, Stored Functions, Stored Triggers
Advantages of Sub Programs:
Provides security
It improves performance
Reduces Network Traffic
Readability gets increases
Code Reusability
Error Detection and modification is quite easy
Extensibility - It will allow a user to increase or decrease the code
STORED PROCEDURES:
SQL Server Supports to work with the following types of procedures
Predefined Procedures (SP_HELP, SP_RENAME…….)
User Defined Stored Procedures
Extended Stored Procedures (XP_CMDSHELL,XP_READMAIL,XP_SENDMAIL)
USER DEFINED STORED PROCEDURES:
It is a stored block Data Base Object which resides in Data Base Server and contains SQL
Statements and Procedural Features.
A procedure in SQL Server 2005 can be made to return value to main program using RETURN
Key Word.
It can be created with and without arguments.
Data can be sent to procedures using INPUT Arguments, after processing that input few
values can be taken back to the main program using OUTPUT Arguments.
A procedure can be set with 1024 INPUT & OUTPUT Arguments.
When a Procedure is set with OUTPUT arguments then it is essential that at sending
arguments also OUPUT should be specified.
OUTPUT Arguments at a procedure which gets data the same will be reflected in main
program.
Procedure Set with INPUT Arguments will work for “call by value” and OUTPUT arguments
will work for “call by reference”
Syntax:
CREATE PROC / PROCEDURE < PROCEDURE_NAME > [(LIST_OF_ARGUMENTS)]
[ WITH ENCRYPTION ]
AS
BEGIN
[ DECLARATION BLOCKS ]
[ EXECUTION BLOCKS ]
[ EXCEPTION HANDLERS]
END
A Procedure can be executed in two ways:
SQL Server 2019 Page: 68 SQL and T-SQL
BEGIN
SELECT * FROM EMP
EXEC RET2
END
EXEC RET1 Output: EMP,SALGRADE,DEPT all three tables will get displayed.
** Up to 32 Levels Procedures can be created.
Q) Create a Procedure called ERET1 that takes EMP No as input and displays ENAME, JOB, SAL and
DEPTNO.
CREATE PROCEDURE ERET1 (@ENO INT)
AS
BEGIN
SELECT ENAME,JOB,SAL,DEPTNO FROM EMP
WHERE EMPNO = @ENO
END
EXEC ERET1 7369
Second Method
CREATE PROCEDURE ERET2 (@ENO INT)
AS
BEGIN
DECLARE @EN VARCHAR(15), @DES VARCHAR(10), @PAY INT, @DNO INT
SELECT @EN = ENAME, @DES = JOB, @PAY = SAL, @DNO = DEPTNO FROM EMP
WHERE EMPNO = @ENO
PRINT @EN
PRINT @DES
PRINT @PAY
PRINT @ENO
PRINT @DNO
END
EXEC ERET2 7369
Third Method
CREATE PROCEDURE ERET3 (@ENO INT ,@EN VARCHAR(15) OUTPUT,
@DES VARCHAR(10) OUTPUT, @PAY INT OUTPUT , @DNO INT OUTPUT)
AS
BEGIN
SELECT @EN = ENAME,@DES = JOB, @PAY = SAL, @DNO = DEPTNO FROM EMP
WHERE EMPNO = @ENO
END
DECLARE @EC INT, @N VARCHAR(10), @J VARCHAR(10),@DC INT, @P INT
SET @EC = 7788
EXEC ERET3 @EC,@N OUTPUT, @J OUTPUT, @DC OUTPUT,@P OUTPUT
PRINT @EC
PRINT @N
PRINT @J
PRINT @DC
PRINT @P
Q) Create a Procedure to insert a record in EMP by checking different validations EMPNO, ENAME,
SAL and DEPTNO.
CREATE PROCEDURE INSROW(@ENO INT,@EN VARCHAR(20),@PAY INT, @DNO INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT, @J INT, @K INT
SELECT @I =COUNT(*) FROM EMP WHERE EMPNO =@ENO
SELECT @J =COUNT(*) FROM DEPT WHERE DEPTNO =@DNO
SELECT @K = MIN(SAL) FROM EMP
IF @I > 0
PRINT 'EMPLOYEE DETAILS ALREADY EXISTS'
ELSE
SQL Server 2019 Page: 70 SQL and T-SQL
IF @J = 0
PRINT 'DEPARTMENT IS NOT AVAILABLE'
ELSE
IF @PAY < @K
PRINT 'INVALID SALARY'
ELSE
BEGIN
BEGIN TRAN
INSERT EMP(EMPNO,ENAME,SAL,DEPTNO) VALUES(@ENO,@EN,@PAY,@DNO)
COMMIT
PRINT 'DETAILS INSERTED SUCCESSFULLY'
END
END
EXEC INSROW 7369,'test',5000,50 --Employee Details Already Exists
EXEC INSROW 73690,'test',5000,50 --Department Is Not Available
EXEC INSROW 73690,'test',5000,10 --Details Inserted Successfully
Q) Create a procedure to update the salary of employee if it is valid increment of more than 500.
CREATE PROCEDURE UPDROW(@ENO INT,@INCR INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT
SELECT @I = COUNT(*) FROM EMP WHERE EMPNO=@ENO
IF @I = 0
PRINT 'EMPLOYEE DOES NOT EXIST'
ELSE
IF @INCR < 500
PRINT 'INVALID INCREMENT'
ELSE
BEGIN
BEGIN TRAN
UPDATE EMP SET SAL=SAL+@INCR WHERE EMPNO=@ENO
COMMIT
PRINT 'ROW UPDATED SUCCESSFULLY'
END
END
EXEC UPDROW 7788,200 -- Invalid Increment
EXEC UPDROW 2001,1200 -- Employee Does Not Exist
EXEC UPDROW 7788,1000 -- Row Updated Successfully
Q) Create a procedure to delete the rows from a table based on valid deptno.
CREATE PROCEDURE DELROW(@DNO INT)
AS
BEGIN
DECLARE @I INT, @J INT
SELECT @I = COUNT(*) FROM DEPT WHERE DEPTNO = @DNO
IF @I = 0
PRINT ' INVALID DEPARTMENT '
ELSE
BEGIN
SELECT @J = COUNT(*) FROM EMP WHERE DEPTNO = @DNO
IF @J = 0
PRINT 'NO EMPLOYEES EXISTS'
ELSE
BEGIN
BEGIN TRAN
DELETE FROM EMP WHERE DEPTNO =@DNO
PRINT CAST(@J AS VARCHAR(10))+' ROWS DELETED SUCCESSFULLY'
END
END
SQL Server 2019 Page: 71 SQL and T-SQL
END
Q) Create a Procedure that performs Bank Transactions provided its implementation on two tables.
CREATE TABLE BANK (ACNO INT,AHN VARCHAR(12),ADDRESS VARCHAR(15),BAL INT)
INSERT BANK VALUES(1001,'HARI','AMRPT',12340)
INSERT BANK VALUES(1007,'KIRAN','BHEL',12900)
INSERT BANK VALUES(1002,'RAJ','ECIL',15400)
INSERT BANK VALUES(1009,'KARAN','AMRPT',23800)
INSERT BANK VALUES(1004,'SUNIL','ABIDS',34900)
CREATE TABLE TRANS (ACNO INT,TT VARCHAR(5),AMOUNT INT,DAT SMALLDATETIME)
CREATE PROC BTRAN(@ACC INT,@TRTY VARCHAR(5),@AMT INT)
AS
BEGIN
SET NOCOUNT ON
DECLARE @I INT,@B INT
SELECT @I = COUNT(*) FROM BANK WHERE ACNO=@ACC
SELECT @B = BAL FROM BANK WHERE ACNO=@ACC
IF @I = 0
PRINT 'INVALID ACCOUNT NUMBER'
ELSE
IF @TRTY = 'D'
BEGIN
BEGIN TRAN
INSERT TRANS VALUES(@ACC,@TRTY,@AMT,GETDATE())
UPDATE BANK SET BAL = BAL+@AMT WHERE ACNO=@ACC
COMMIT
PRINT 'ROW INSERTED AND UPDATED SUCCESSFULLY'
END
ELSE
BEGIN
IF @TRTY = 'W'
BEGIN
IF @AMT > @B
PRINT 'OVER DRAFT OF AMOUNT'
ELSE
IF @AMT > @B-500
PRINT 'INVALID TRANS - MIN BAL SHOULD BE 500'
ELSE
IF @AMT < 100
PRINT 'INVALID AMOUNT'
ELSE
BEGIN
BEGIN TRAN
INSERT TRANS VALUES(@ACC,@TRTY,@AMT,GETDATE())
UPDATE BANK SET BAL=BAL-@AMT WHERE ACNO=@ACC
COMMIT
PRINT 'ROW INSERTED AND UPDATED SUCCESSFULLY'
END
END
ELSE
PRINT 'INVALID TRANSACTION TYPE'
END
END
MODIFYING THE PROCEDURE
ALTER PROC/PROCEDURE < PROCEDURE_NAME >([LIST_OF_ARGS])
[WITH ENCRYPTION]
AS
BEGIN
STATEMENTS
END
SQL Server 2019 Page: 72 SQL and T-SQL
BEGIN
INSERT EMP(EMPNO,SAL) SELECT EMPNO,M_SAL FROM INSERTED
END
To display list of triggers created in a database:
SELECT NAME FROM SYSOBJECTS WHERE XTYPE='TR'
VIEWING TRIGGER INFORMATION:
SP_HELPTEXT < TRIGGER_NAME >
DISABLE / ENABLE THE TRIGGERS:
ALTER TABLE < TABLE_NAME > DISABLE/ENABLE TRIGGER < TRIGGER_NAME>
TO DISABLE DATABASE OR DML TRIGGERS:
DISABLE/ENABLE TRIGGER < TRIGGER_NAME > [ALL] ON DATABASE /
OBJECT_NAME
DROPING A TRIGGER: DROP TRIGGER < TRIGGER_NAME > ON < DATABASE_NAME >
CURSORS
It creates a temporary memory at database server to store result set of a query.
It is created at a system database TempDB
Cursors will create a memory to store multiple rows that are returned by a SELECT query.
Cursors are Created based on the following steps:
Declaring a Cursor
Opening a Cursor
Fetching the data from a Cursor
Closing a Cursor
Deallocating a Cursor
DECLARING A CURSOR:
A cursor is declared by its name associated with a standard SELECT query using DECLARE keyword. It
stores a query for retrieving all rows of a table or retrieving the rows on conditional basis. It also
includes navigation of cursor, type of cursor and type of lock provided on cursor.
Syntax:
DECLARE < CURSOR_NAME > /VAR CURSOR
NAVIGATION_TYPE FORWARD / SCROLL
CURSOR_TYPE STATIC / KEYSET / DYNAMIC / FAST FORWARD
LOCK_TYPE READONLY / SCROLL LOCK / OPTIMISTIC
FOR SELECT QUERY
**By default a cursor is FORWARD only cursor, which supports to access the cursor sequentially.
**If navigation type is provided as SCROLL then can access cursor randomly.
CURSOR TYPES: SQL SERVER will support to create a cursor with any of the following types;
STATIC: When this cursor type is specified it will not make the changes in the cursor when
the table is changed in a database.
KEYSET: When this cursor type is specified it will make the changes in a cursor when the
table is provided with the changes thru DML operations.
DYNAMIC: When this cursor type is specified it also makes the changes in cursor when the
table is changed in a database but performance gets decreases.
FAST FORWARD: When this cursor type is specified it will work similar to KEYSET and
provides fast performance.
LOCKS provided on Cursor:
READ ONLY (Shared Lock): When this lock is provided cursor will not accept any changes into it.
SCROLL LOCK (Exclusive Lock): It will allow to make modifications but only by one user.
OPTIMISTIC: It will allow to make modifications but only by multiple users.
OPENING A CURSOR:
A cursor which is created when gets opened; the query which is associated gets executed and makes
the data available in a cursor.
SQL Server 2019 Page: 78 SQL and T-SQL
END
CLOSE C1
DEALLOCATE C1
Q) Write a program to create SCROLL cursor and access first and last records of EMP table.
DECLARE @ENO INT,@EN VARCHAR(12),@DNO INT
DECLARE C1 CURSOR SCROLL FOR SELECT EMPNO,ENAME,DEPTNO FROM EMP
OPEN C1
FETCH FIRST FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS = 0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+' '+@EN+' '+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
FETCH LAST FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS=0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+' '+@EN+' '+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
CLOSE C1
DEALLOCATE C1
Q) Write a program to display required record from a cursor using absolute position.
DECLARE @ENO INT,@EN VARCHAR(12),@DNO INT
DECLARE C1 CURSOR SCROLL FOR SELECT EMPNO,ENAME,DEPTNO FROM EMP
OPEN C1
FETCH ABSOLUTE 3 FROM C1 INTO @ENO,@EN,@DNO
FETCH RELATIVE 2 FROM C1 INTO @ENO,@EN,@DNO
IF @@FETCH_STATUS=0
BEGIN
PRINT CAST(@ENO AS VARCHAR(10))+' '+@EN+' '+CAST(@DNO AS
VARCHAR(12))
END
ELSE
BEGIN
PRINT 'FETCHING FAILED'
END
CLOSE C1
DEALLOCATE C1
Note:
When RELATIVE position is specified with +Ve value, it moves the record pointer from
current position to the next record in forward direction.
If -Ve value is specified it moves the record pointer in backward direction from current
position. To the current position relative position is added or subtracted and then takes the
control to the next record.
Q) Write a program to delete all tables from a Database.
DECLARE C2 CURSOR FOR SELECT NAME FROM SYS.TABLES
DECLARE @TN VARCHAR(12)
OPEN C2
FETCH NEXT FROM C2 INTO @TN
WHILE @@FETCH_STATUS <>-1
SQL Server 2019 Page: 80 SQL and T-SQL
BEGIN
EXEC('DROP TABLE '+@TN)
FETCH NEXT FROM C2 INTO @TN
END
CLOSE C2
DEALLOCATE C2
CLR INTEGRATION
In SQL Server 2005 Database Engine is integrated with CLR (Common Language Runtime
Environment) Database objects can be created with T-SQL Code + DOT NET Language Code.
A Database object created with T-SQL + DOT NET Language Code can be called as CLR Database
Object
CLR Stored Procedure
CLR Stored Functions
CLR Stored Triggers
CLR User Defined Types
CLR User Defined Aggregates
To prepare CLR Database object we have to follow four steps.
Develop .NET Assembly
Register the Assembly in SQL Server 2005.
Convert the Assembly methods into SP’s, SF’s, ST’s etc.
Invoke the Object through SQL Server.
CLR Function with C#
using.system;
using.system.collections.generic;
using.system.text;
using.system.data;
using.system.data.SQLClients;
using.system.data.SQLTypes;
using.microsoft.SQLserver.server;
Public Class CLRClass
{
[MS SQL Server SQL Function]
Public Static Int MyCLRMethod (int a, int b)
{
return (a+b);
}
}
Step 2: Register the Assembly in SQL Server.
GUI
Step 1: Select the Database
Step 2: Click on Programmability
Step 3: Click on New Assembly
Step 4: Provide the Path of the Compiled C# DLL File
Query Based
CREATE ASSEMBLY MYCLRASSEMBLY FROM 'C:MYCLR\BIN\DEBUG\MYCLR.DLL'
WITH PERMISSION_SET = SAFE
PERMISSION_SET = SAFE / UNSAFE / EXTERNALACCESS
CREATE FUNCTION MYCLRTEST(@I INT, @J INT)
RETURNS INT
AS
EXTERNAL NAME
MYCLRASSEMBLY.CLRCLASS.MYCLRMETHOD
SQL Server 2019 Page: 81 SQL and T-SQL
SELECT DBO.MYCLRTEST(27,89)
ENABLE/DISABLE CLR Integration:
Step 1: Microsoft SQL Server
Step 2: Configuration Tools
Step 3: SQL Server Surface Area Configuration
Step 4: Surface Area Configuration Features
Step 5: CLR Integration
Step 6: Enable the CLR
Or
SP_CONFIGURE 'SHOW_ADVANCED OPTIONS',1
SP_CONFIGURE 'CLR ENABLED',1
1- ENABLE, 0 - DISABLE
XML INTEGRATION
In SQL SERVER 2005 XML integration is introduced, which supports to store and access the data in
XML format.
Retrieving the table data in XML Format:
The data in a table which is in the form of rows and columns can be displayed in XML Format using
FOR XML clause of SELECT Statement.
Syntax:
SELECT .....................
FROM TABLE1...........
FOR XML <RAW / AUTO / PATH>, ROOT (NAME)
SELECT EMPNO,ENAME,DEPTNO FROM EMP FOR XML RAW
Output: <row EMPNO="7369" ENAME="SMITH" DEPTNO="20" />
<row EMPNO="7499" ENAME="ALLEN" DEPTNO="30" />
<row EMPNO="7521" ENAME="WARD" DEPTNO="30" />
SELECT EMPNO,ENAME,DEPTNO FROM EMP FOR XML AUTO,ROOT('EMPINFO')
Output:
<EMPINFO>
<EMP EMPNO="7369" ENAME="SMITH" DEPTNO="20" />
<EMP EMPNO="7499" ENAME="ALLEN" DEPTNO="30" />
<EMP EMPNO="73690" ENAME="test" DEPTNO="10" />
</EMPINFO>
SELECT EMPNO,ENAME,DEPTNO FROM EMP FOR XML PATH,ROOT('EMPINFO')
Output: <EMPINFO>
<row>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<DEPTNO>20</DEPTNO>
</row>
<row>
<EMPNO>7499</EMPNO>
<ENAME>ALLEN</ENAME>
<DEPTNO>30</DEPTNO>
</row>
</EMPINFO>
Storing XML data into table:
Data which is represented in XML format can be stored into a table in the form of rows and
columns using OPENXML ()
XML data is converted in table format by creating a temporary memory and it is done by
using a predefined procedure.
EXEC SP_XML_PREPAREDOCUMENT ARG1 OUTPUT, ARG2
Arg1 is a pointer to that temporary memory table which stores the address
of that table. It can be used when that temporary table is to be removed.
Arg2 is a variable which contains the data in XML format.
SQL Server 2019 Page: 82 SQL and T-SQL
Session 1:
BEGIN TRAN EXCLUSIVE
UPDATE EMP SET ENO = 200
SELECT RESOURCE_TYPE, REQUEST_MODE FROM SYS.DM_TRAN_LOCKS
WHERE RESOURCE_TYPE <> 'DATABASE'
WAITFOR DELAY '00:00:15'
Session 2:
SELECT * FROM EMPL WITH (NOLOCK)
ISOLATION LEVELS:
These are classified in four types:
READ COMMITTED
READ UNCOMMITTED
REPEATABLE READ
SERIALIZABLE
**By Default a transaction isolation level is “READ COMMITED”
DataReads:
Dirty Read – A Dirty read is the situation when a transaction reads a data that has not yet been committed.
For example, Let’s say transaction 1 updates a row and leaves it uncommitted, meanwhile, Transaction 2 reads
the updated row. If transaction 1 rolls back the change, transaction 2 will have read data that is considered
never to have existed.
Non Repeatable read – Non Repeatable read occurs when a transaction reads same row twice, and get a
different value each time. For example, suppose transaction T1 reads data. Due to concurrency, another
transaction T2 updates the same data and commit, Now if transaction T1 rereads the same data, it will
retrieve a different value.
Phantom Read – Phantom Read occurs when two same queries are executed, but the rows retrieved by the
two, are different. For example, suppose transaction T1 retrieves a set of rows that satisfy some search
criteria. Now, Transaction T2 generates some new rows that match the search criteria for transaction T1. If
transaction T1 re-executes the statement that reads the rows, it gets a different set of rows this time
Read Uncommitted – Read Uncommitted is the lowest isolation level. In this level, one transaction may read
not yet committed changes made by other transaction, thereby allowing dirty reads. In this level, transactions
are not isolated from each other.
Read Committed – This isolation level guarantees that any data read is committed at the moment it is read.
Thus it does not allows dirty read. The transaction holds a read or write lock on the current row, and thus
prevent other transactions from reading, updating or deleting it.
Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it
references and writes locks on all rows it inserts, updates, or deletes. Since other transaction cannot read,
update or delete these rows, consequently it avoids non-repeatable read.
Serializable – This is the highest isolation level. A serializable execution is guaranteed to be serializable.
Serializable execution is defined to be an execution of operations in which concurrently executing transactions
appears to be serially executing.
Syntax:
SET TRANSACTION ISOLATION LEVEL < LEVEL_TYPE >
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM EMPL
BULK COPY PROGRAM
The Bulk Copy Program Utility in SQL Server enables Database administrator to import bulk
data into a table or export it from a table into a file.
It also supports several options that define how data will be imported. Where it will be
imported and which data will be loaded.
BCP Commands will allow a user to Bulk Copy Data “IN” & “OUT” of SQL Server Tables.
SQL Server 2019 Page: 85 SQL and T-SQL
Syntax:
BCP < Source.DB > IN / OUT < Destination file > [Options]
IN – Import, OUT – Export
Options are Case Sensitive
-T --- Trusted Connection (Windows Authentication)
-S --- Server Name
-U ---User Name
-P --- Password (SQL Server Authentication)
-c --- Character Format
-r --- Row Terminator (CR-LF) Carriage Return Line Field
-E --- Field Terminator (Tab Default)
Exporting data with BCP Utility one of the simplest operations that can perform with BCP is to bulk
copy data out of a SQL Server table into a Text File
Exporting data through Query
BCP “SELECT * FROM TESTDB.DBO.EMP” QUERYOUT C:\emp.csv –c –T -t
Importing Data: To Import the data of a file into a table create at SQL Server, BCP will provide an
option called “IN”
BCP testdb.dbo.emp IN C:\emp.csv –c –T –t -E
BACKUP & RECOVERY OF A DATABASE
Backup of a Database: As system is an electronic device, at any point of time it may come across
with a problem in hardware or at Operating System or at Database, due to which data available in
Database may be lost.
In order to have security for data and Database objects. It is essential that at the End of the Day to
go for a Backup. It creates a backup of Database in to Flat Files. Backup Data later can be transferred
into other external devices for security reasons.
Backup is done in different ways
Full Backup
Differential Backup
Files & File Groups
Transaction Logs
Syntax:
BACKUP DATABASE <DATABASE_NAME>
TO DISK ='FILEPATH.BAK'
Syntax:
BACKUP DATABASE <DATABASE_NAME>
TO DISK ='FILEPATH.BAK'
WITH DIFFERENTIAL
Restore of Database: Database can be restored in a same system or it can be on different system.
Syntax:
RESTORE DATABASE <DATABASE_NAME>
FROM DISK ='FILEPATH.BAK'
Note: for Restoring the Query to be executed using master database
EXTENDED STORED PROCEDURES:
A Stored Procedure contains T-SQL Statements and C/C++ Code compiled into DLL file is called
Extended Stored Procedure. Every Extended Stored Procedure starts with XP. All Extended Stored
Procedures are stored in masterdb.
Extended Stored Procedures are used to perform operations in Operating system and Mail Server.
XP_CMDSHELL (Operating System Command) it is used to communicate with Operating System to
execute commands.
Note: to work with this extended procedure it should be enable at configuration tools
SP_CONFIGURE 'CMDSHELL',1
SQL Server 2019 Page: 86 SQL and T-SQL
RECONFIGURE
XP_CMDSHELL 'DIR C:\'
XP_CMDSHELL 'MD C:\NEW'
XP_SENDMAIL, XP_READMAIL are used to interact with mailing servers.
DEPLOYMENT OF DATABASE: The process of copying database objects structures with data from
one server to another server is called Deployment of Database.
Method 1:
Copy Backup file (.BAK) to destination system and return it on destination system.
Method 2:
Copy Data Files and Log Files to destination system.
Detach the Database on Source System
SP_DETACH_DB <DATABASE_NAME>
Copy the Database Files to same location on destination system.
Attach these files to a Database on destination system
CREATE DATABASE < DATABASE_NAME >
ON
FILENAME = 'FILE_PATH'
FOR ATTACH
Method 3:
Creating a Batch and Script Files:
Batch is nothing but set of T-SQL Statements executed under single execution plan.
Every Batch is followed by GO (which makes a separate execution plan) Creation of any
Objects, setting any property should be presented in different batches.
Script is nothing but collection of batches saved in a file with .SQL extension.
Advantages:
Script files are reusable.
Script files are used to copy database objects from one system to another system.
Generating T-SQL Scripts for existing Database SQL Server provides Script wizard to generate scripts
for existing Database and other objects.
Select Database
Click on Tasks
Click on Generate Scripts - Click Next
Select Database Name - Click Next
Check Scripts all objects in Database - Click Next
Provides Scripting options
Append to File = True (If True Select Existing File)
Script Database Create = True (If True Create Database statement generated)
(If False Create Database Statement will not generated)
Script for server version SQL Server 2005
Click Finish
DATA TRANSFORMATION SERVICE or SQL SERVER INTEGRATION SERVICES
In SQL Server 2000 we have DTS Packages which are based on COM Technology (Component Object
Model)
In SQL Server 2005 it is introduced as SSIS package based on DOTNET Technology.
To import or export Database objects and data from one source to another data source we
can use DTS or SSIS Package.
SSIS Package will support to import or export the database and data between following software’s.
SQL Server ------------ MS Access
SQL Server ------------ Oracle
SQL Server ------------ SQL Server
SQL Server ------------ Text File/XML Files/Excel Files etc
SQL Server 2019 Page: 87 SQL and T-SQL
DTS/SSIS communicates with any data source with the help of ODBC or OLEDB or DOTNET data
providers.
Note: SSIS Package’s will be stored in MSDB Database.
SQL Native Client: Interface can be used to communicate with only SQL Server
Exporting data from SQL Server to Excel Sheet
Select Database
Right Click on Select Export Data - Click Next
Specify Source Data
Data Source: SQL Native Client
Server Name: Sys-PC
Database: TestDB - Click Next
Specify Destination
Destination: MS EXCEL
File Path: ‘C:\Testexcel.xls ’
Check First row has column names - Click Next
Select Copy data from one or more tables or views - Click Next
Select Tables/ Views whose data is to be copied into Excel sheet - Click Next
Check Execute Immediately
Click Finish
Importing data from SQL Server to SQL Server
Select Database (Destination Database)
Right Click on Select Import Data - Click Next
Specify Source Data
Data Source: SQL Native Client
Server Name: Sys-PC
Database: TestDB - Click Next
Specify Destination
Destination: SQL Native Client
Server Name: Sys-PC
Database: TestDB1 - Click Next
Select Copy data from one or more tables or views - Click Next
Select Tables/ Views whose data is to be copied into Excel sheet - Click Next
Check Execute Immediately
Click Finish
Browsing SSIS packages
Object Explore
Connect to Integration Services
Select Stored Packages
MSDB (System Database)
Select Package and Run Package
SQL SERVER AGENT
In SQL Server 2005 SQL Server Agent is a service, it supports to create jobs, schedules, alerts
and operations.
It provides automatic execution of Jobs and Tasks associated with different steps
automatically based on system date, Day and Time.
To work with SQL Server Agent it is essential that services should get start.
To start the Service
Start - Programs – SQL Server – Configuration Tools – SQL Server Configuration Manager – Select SQL
Server Manager and Click Start
Example:
SQL Server 2019 Page: 88 SQL and T-SQL
Create a table
CREATE TABLE SSA(ID INT IDENTITY, DATE SMALLDATETIME())
To Work with SQL Server Agent:
Object Explorer
Click on SQL Server Agent
Step 1:
New Job
Name: INS_REC_JOB
Owner: SA
Category [uncategorized (local)]
Step 2:
Select Steps from select a page window
Click New
Step Name: INS_REC
Type: T-SQL Script
Database: TestDB
Command: INSERT SSA VALUES (GETDATE())
Step 3:
Select Schedule from select a page Window
Click New
Name: SCH_INS_REC
Schedule Type: Recurring
Frequency Occurs: Daily
Click Finish
SQL SERVER REPORTING SERVICES
It is a server based reporting generation software system from Microsoft. It can be used to
prepare and deliver a variety of interactive and printed reports.
It is administrated via a web interface reporting services features a web service interface to
support the development of custom reporting applications.
SSRS Competes with crystal reports and other business intelligence tools and it is included in
express, workgroup, standard and enterprise edition of SQL Server as an install option.
Reporting services was first released in 2004 as an add-on to SQL Server 2000.
The Second version was released as a part of SQL Server 2005 in November 2005.
The latest version was released as part of SQL Server 2008 in August 2008.
Reporting services frame work contains the following components.
Report Server
Report Manager
Report Temporary Database
Report Server: It compiles and executes client requests connecting to different data sources and
loads the required data in to temporary database.
Report Manager: It will verify security information connections information of client.
Report Temporary Database: To store the reporting data temporary for processing purpose.
Generating Sample Reports:
Starting the Service: Configuration Tools – SQL Server Configuration Manager –SSRS
Generating the Report
SQL Server 2005 – SQL Server Business Intelligence Development Studio
Step 1:
Click on File –New Project – Report Server Project Wizard
Name: User Report
Location: C:\TestReport
SQL Server 2019 Page: 89 SQL and T-SQL
Brings built-in support for providing information about data stored in the table at any point in
time rather than only the data that is correct at the current moment in time.
Works along with SQL AUDIT for Complete data change history (WHO, WHAT, WHEN)
Primary key must be on table on which we are trying to create Temporal Table.
Also called System Versioned temporal table
CREATE TABLE Department
(
DeptID int NOT NULL PRIMARY KEY CLUSTERED
, DeptName varchar(50) NOT NULL
, ManagerID INT NULL
, ParentDeptID int NULL
, SysStartTime datetime2 GENERATED ALWAYS AS ROW START NOT NULL
, SysEndTime datetime2 GENERATED ALWAYS AS ROW END NOT NULL
, PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
)
WITH
(
SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.DepartmentHistory)
)
;
Custom Masking method which exposes the first and last XXXXXXX8967
String letters and adds a custom padding string in the
middle.
Row-Level Security enables customers to control access to rows in a database table based on the
characteristics of the user executing a query (e.g., group membership or execution context).
Row-Level Security (RLS) simplifies the design and coding of security in your application. RLS
enables you to implement restrictions on data row access.
The access restriction logic is located in the database tier rather than away from the data in
another application tier.
--DROP USER IF EXISTS Manager;
--DROP USER IF EXISTS Sales1;
--DROP USER IF EXISTS Sales2;
CREATE USER Manager WITHOUT LOGIN;
CREATE USER Sales1 WITHOUT LOGIN;
CREATE USER Sales2 WITHOUT LOGIN;
JSON Support
JSON, short for JavaScript Object Notation, is based on a subset of the JavaScript programming
language and is noted for being human readable and easy for computers to parse and generate.
A lightweight format for exchanging data between different source types, similar to how XML is
used.
SQL Server 2016 includes no JSON-specific data type and consequently none of the kinds of
methods available to the XML data type. SQL Server 2016 continues to use the NVARCHAR type
to store JSON data.
JSON support introduced in SQL server 2016 to convert JSON into Relational data and vice versa.
{
"FirstName":null,
"LastName":"Duffy",
"NatID":245797967,
"Current":false,
"Skills":["Dev","QA","PM"],
"Region":{"Country":"Canada","Territory":"North America"}
}';
SELECT [Key],Value FROM OPENJSON(@json);
DECLARE @json NVARCHAR(MAX)='{
"Employees":[
{
"Name":{
"First":"Terri",
"Middle":"Lee",
"Last":"Duffy"
},
"PII":{
"DOB":"1971-08-01",
"NatID":"245797967"
},
"LoginID":"adventure-works\\terri0"
},
{
"Name":{
"First":"Roberto",
"Middle":null,
"Last":"Tamburello"
},
"PII":{
"DOB":"1974-11-12",
"NatID":"509647174"
},
"LoginID":"adventure-works\\roberto0"
}
]
}'
SELECT *
FROM OPENJSON(@json, '$.Employees')
WITH(FirstName NVARCHAR(25) '$.Name.First',
MiddleName NVARCHAR(25) '$.Name.Middle',
LastName NVARCHAR(25) '$.Name.Last',
BirthDate DATE '$.PII.DOB',
NationalID INT '$.PII.NatID');
PolyBase
SQL Server 2019 Page: 95 SQL and T-SQL
PolyBase enables your SQL Server 2016 instance to process Transact-SQL queries that read data
from Hadoop.
PolyBase external access is not limited to Hadoop. Other unstructured non-relational tables are
also supported, such as delimited text files.
Query both sources of data, then write custom query logic to join and integrate the data at the
client level
STRETCH DATABASE
Interesting solution to where to put that historical data without taking up valuable disk space or
prolonging backups.
Queries don’t change, SQL combines local and ‘stretched’ data.
SQL Server 2019 Page: 96 SQL and T-SQL
ALWAYS ENCRYPTED
Always Encrypted is a client-side encryption technology that Microsoft introduced with SQL
Server 2016
Always Encrypted requires your client application to use an Always Encrypted-enabled driver to
communicate with the database.
Even SQL admins not able to read the data and Secret key never passed to SQL server.
SQL Server 2019 Page: 97 SQL and T-SQL
Very effective feature if you are using cloud based Azure data storage