USE WideWorldImporters
-- Create Transact-SQL SELECT queries
-- 001
SELECT *
FROM Orders
-- 002
SELECT name
FROM sys.servers
WHERE server_id = 0
-- 003
SELECT *
FROM [DESKTOP-LO5S40T].Wideworldimporters.sales.orders
-- 004
SELECT d.name
,MAX(b.backup_finish_date) AS 'Most recent full backup'
FROM master.sys.databases d
LEFT OUTER JOIN msdb..backupset b ON d.name = b.database_name
WHERE d.name <> 'tempdb'
AND (b.type = 'D' OR b.type IS NULL)
GROUP BY d.name
ORDER BY d.name;
-- 005
CREATE TABLE dbo.Orders (id int)
SELECT *
FROM dbo.Orders
DROP TABLE dbo.Orders
-- 006
SELECT name
,default_schema_name
FROM sys.database_principals
WHERE principal_id = user_id();
-- 007
CREATE SYNONYM [dbo].[Orders] FOR [WideWorldImporters].[Sales].[Orders]
SELECT *
FROM dbo.Orders
-- 008
DROP SYNONYM [dbo].[Orders]
-- 009
SELECT master.sys.databases.name
-- 010
SELECT o.*
FROM (SELECT * FROM Sales.Orders) o
-- SELECT clause
-- 011
SELECT OrderID as 'Order number'
FROM Sales.Orders
SELECT 'Order number' = OrderID
FROM Sales.Orders
-- 012
SELECT UPPER(FullName)
FROM [Application].[People]
--WHERE clause
-- 013
SELECT *
FROM [Application].[People]
WHERE PersonID = 1
-- 014
SELECT *
FROM [Application].[People]
WHERE FullName = 'Kayla Woodcock'
-- 015
SELECT *
FROM [Application].[People]
WHERE EmailAddress = NULL
-- 016
SELECT *
FROM [Application].[People]
WHERE EmailAddress IS NULL
-- 017
SELECT *
FROM [Application].[People]
WHERE FullName LIKE 'Daniel%'
-- 018
SELECT *
FROM [Application].[People]
WHERE PreferredName LIKE 'Isabell_'
-- 019
SELECT *
FROM [Application].[People]
WHERE PreferredName LIKE 'Isabell[a-z]'
-- 020
SELECT *
FROM [Application].[People]
WHERE PreferredName IN ('Isabelle', 'Isabell')
-- 021
SELECT *
FROM [Application].[People]
WHERE PreferredName IN ( SELECT CustomerName
FROM sales.Customers )
-- 022
SELECT *
FROM [Application].[People]
WHERE PreferredName BETWEEN 'I' AND 'Isabelle'
-- 023
SELECT *
FROM [Application].[People]
WHERE PersonID BETWEEN 1 AND 10
-- 024
SELECT GETDATE()
-- 025
SELECT *
FROM [Application].[People]
WHERE ValidTo > GETDATE()
-- 026
SELECT LEFT('Isabelle', 3)
-- 027
SELECT *
FROM [Application].[People]
WHERE LEFT(PreferredName,3) = 'Isa'
SELECT *
FROM [Application].[People]
WHERE PreferredName LIKE 'Isa%'
-- 028
DECLARE @FirstName varchar(50)
SET @FirstName = 'Isabelle'
SELECT *
FROM [Application].[People]
WHERE PreferredName = @FirstName
SELECT *
FROM [Application].[People]
WHERE PreferredName = 'Isabelle'
-- 029
DECLARE @FullName varchar(50)
SELECT @FullName = FullName
FROM [Application].[People]
WHERE PreferredName = 'Isabelle'
SELECT @FullName
-- 030
SELECT *
FROM [Application].[People]
WHERE 1 = 1
-- 031
SELECT *
FROM [Application].[People]
WHERE PersonID = 1
AND PersonID = 2
-- 032
SELECT *
FROM [Application].[People]
WHERE PersonID = 1
OR PersonID = 2
--033
SELECT *
FROM [Application].[People]
WHERE PersonID IN (1, 2)
-- 034
SELECT *
FROM [Application].[People]
WHERE (PersonID = 1
OR PersonID = 2)
AND PreferredName = 'Isabella'
SELECT *
FROM [Application].[People]
WHERE PersonID = 1
OR (PersonID = 2
AND PreferredName = 'Isabella')
/* ORDER BY clause */
-- 035
SELECT *
FROM [Application].[People]
ORDER BY PreferredName
-- 036
SELECT *
FROM [Application].[People]
ORDER BY PreferredName DESC
-- 037
SELECT *
FROM [Application].[People]
ORDER BY PreferredName, PersonID
-- 038
SELECT PreferredName
FROM [Application].[People]
ORDER BY ValidFrom
/* Set operators */
-- 039
SELECT 1, 'record 1'
UNION
SELECT 2, 'record 2'
-- 040
SELECT 1, 'record 1'
UNION
SELECT 1, 'record 2'
SELECT 1, 'record 1'
UNION ALL
SELECT 1, 'record 2'
-- 041
SELECT 1, 'record 1' as Alias1
UNION
SELECT 2 as Alias2, 'record 2' as Alias3
-- 042
SELECT 1, 'record 1'
UNION
SELECT 2 , GETDATE()
-- 043
SELECT 1, 'record 1'
EXCEPT
SELECT 1, 'record 1'
-- 044
SELECT 1, 'record 1'
INTERSECT
SELECT 1, 'record 1'
-- 045
USE TestDB
GO
CREATE TABLE dbo.Customers
(
CustomerID tinyint NOT NULL IDENTITY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
-- 046
CREATE TABLE dbo.Employees
(
EmployeeID tinyint NOT NULL IDENTITY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
-- 047
INSERT dbo.Customers VALUES ('Bob', 'Jackson', 'Main street 1, Dallas');
INSERT dbo.Customers VALUES ('Frank', 'Smith', 'Second street 2, Miami');
INSERT dbo.Customers VALUES ('Joe', 'Johnson', 'Third Avenue 3, New York');
INSERT dbo.Employees VALUES ('Jack', 'Ford', 'Second street 2, Denver');
INSERT dbo.Employees VALUES ('Donald', 'Charleston', 'Times Square, New York');
INSERT dbo.Employees VALUES ('Bob', 'Jackson', 'Main street 1, Dallas');
-- 048
SELECT FirstName, LastName, Address
FROM Customers
UNION
SELECT FirstName, LastName, Address
FROM Employees
-- 049
DROP TABLE dbo.Customers;
DROP TABLE dbo.Employees;
/* Section 2: Querying multiple tables by using joins */
-- 050
SELECT *
FROM Sales.Orders
,Sales.OrderLines
-- 051
SELECT *
FROM Sales.Orders
CROSS JOIN Sales.OrderLines
-- 052
SELECT *
FROM Sales.Orders
,Sales.OrderLines
WHERE Sales.Orders.OrderID = Sales.OrderLines.OrderID
-- 053
SELECT *
FROM Sales.Orders o
,Sales.OrderLines ol
WHERE o.OrderID = ol.OrderID
-- 054
SELECT *
FROM Sales.Orders o
,Sales.OrderLines ol
WHERE o.OrderID = ol.OrderID
AND o.OrderDate = '2014-07-17'
-- 055
SELECT *
FROM Sales.Orders o
JOIN Sales.OrderLines ol ON o.OrderID = ol.OrderID
WHERE o.OrderDate = '2014-07-17'
-- 056
SELECT *
FROM warehouse.StockItems
WHERE StockItemID NOT IN ( SELECT StockItemID
FROM sales.Orderlines)
-- 057
CREATE TABLE dbo.Customers
(
CustomerID tinyint NOT NULL IDENTITY PRIMARY KEY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
CREATE TABLE dbo.Orders
(
OrderID tinyint NOT NULL IDENTITY PRIMARY KEY
,CustomerID tinyint NOT NULL
,OrderDate datetime NOT NULL
,SalesAmount decimal(18,2) NOT NULL
);
INSERT dbo.Customers VALUES ('Bob', 'Jackson', 'Main street 1, Dallas');
INSERT dbo.Customers VALUES ('Frank', 'Smith', 'Second street 2, Miami');
INSERT dbo.Customers VALUES ('Joe', 'Johnson', 'Third Avenue 3, New York');
INSERT dbo.Orders VALUES (1, '2011-01-01', 30.02);
INSERT dbo.Orders VALUES (2, '2012-02-02', 15.99);
INSERT dbo.Orders VALUES (4, '2014-04-04', 107.00);
-- 058
SELECT *
FROM dbo.Customers c
LEFT OUTER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
-- 059
SELECT *
FROM dbo.Customers c
RIGHT OUTER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
-- 060
INSERT dbo.Orders VALUES (1, '2015-05-05', 230.02);
-- 061
SELECT *
FROM dbo.Customers c
FULL OUTER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
-- 062
CREATE TABLE dbo.OrderLines
(
OrderLineID tinyint NOT NULL
,OrderID tinyint NOT NULL
,Product varchar(100) NOT NULL
,Units tinyint NOT NULL
,UnitPrice decimal(18,2) NOT NULL
);
INSERT dbo.OrderLines VALUES (1, 1, 'ProductA', 1, 10.04);
INSERT dbo.OrderLines VALUES (2, 1, 'ProductB', 2, 9.99);
-- 063
SELECT *
FROM dbo.Customers c
INNER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
LEFT OUTER JOIN dbo.OrderLines ol on ol.OrderID = o.OrderID;
-- 064
SELECT c.FirstName
,c.LastName
,o.OrderDate
,o.SalesAmount
,ol.Product
,ol.Units
,ol.UnitPrice
FROM dbo.Customers c
INNER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
LEFT OUTER JOIN dbo.OrderLines ol on ol.OrderID = o.OrderID
ORDER BY c.CustomerID, o.OrderID, ol.OrderLineID;
-- 065
DROP TABLE dbo.Customers;
DROP TABLE dbo.Orders;
DROP TABLE dbo.OrderLines;
-- Construct multiple JOIN operators using AND and OR
-- 066
CREATE TABLE dbo.Customers
(
FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
ALTER TABLE dbo.Customers ADD CONSTRAINT PK_Customers
PRIMARY KEY (FirstName, LastName)
GO
CREATE TABLE dbo.Orders
(
OrderID tinyint NOT NULL IDENTITY PRIMARY KEY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,OrderDate datetime NOT NULL
,SalesAmount decimal(18,2) NOT NULL
);
INSERT dbo.Customers VALUES ('Bob', 'Jackson', 'Main street 1, Dallas');
INSERT dbo.Customers VALUES ('Frank', 'Smith', 'Second street 2, Miami');
INSERT dbo.Customers VALUES ('Joe', 'Johnson', 'Third Avenue 3, New York');
INSERT dbo.Orders VALUES ('Bob', 'Jackson', '2011-01-01', 30.02);
INSERT dbo.Orders VALUES ('Frank', 'Smith', '2012-02-02', 15.99);
INSERT dbo.Orders VALUES ('Bob', 'Smith', '2014-04-04', 107.00);
-- 067
SELECT *
FROM dbo.Customers c
FULL OUTER JOIN dbo.Orders o
ON c.FirstName = o.FirstName AND c.LastName = o.LastName
-- 068
DROP TABLE dbo.Customers;
DROP TABLE dbo.Orders;
-- 069
CREATE TABLE dbo.Student
(
CustomerID tinyint NOT NULL IDENTITY PRIMARY KEY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,FatherID tinyint NOT NULL
,MotherID tinyint NOT NULL
,IsCurrent bit NOT NULL
);
CREATE TABLE dbo.Parent
(
ParentID tinyint NOT NULL IDENTITY PRIMARY KEY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,EmailAddress varchar(100) NULL
);
INSERT dbo.Student VALUES ('Bob jr', 'Jackson', 1,2, 0);
INSERT dbo.Student VALUES ('Joe jr', 'Johnson', 3,4, 1);
INSERT dbo.Parent VALUES ('Bob sr', 'Jackson', NULL);
INSERT dbo.Parent VALUES ('Betty', 'Jackson', 'bettyjackson@someprovider.com');
INSERT dbo.Parent VALUES ('Joe sr', 'Johnson', 'joejohnson@someprovider.com');
INSERT dbo.Parent VALUES ('Jane', 'Johnson', 'janejohnson@someprovider.com');
-- 070
SELECT s.FirstName AS 'Student first name'
,s.LastName AS 'Student last name'
,p.FirstName AS 'Parent first name'
,p.LastName AS 'Parent last name'
,p.EmailAddress
FROM dbo.Student s
inner join Parent p on s.FatherID = p.ParentID OR s.MotherID = p.ParentID
WHERE s.IsCurrent = 1
-- 071
DROP TABLE dbo.Student
DROP TABLE dbo.Parent
-- Write queries with NULLs on joins
-- 072
CREATE TABLE dbo.Customers
(
CustomerID tinyint NULL
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
CREATE TABLE dbo.Orders
(
OrderID tinyint NOT NULL IDENTITY PRIMARY KEY
,CustomerID tinyint NULL
,OrderDate datetime NOT NULL
,SalesAmount decimal(18,2) NOT NULL
);
INSERT dbo.Customers VALUES (1, 'Bob', 'Jackson', 'Main street 1, Dallas');
INSERT dbo.Customers VALUES (2, 'Frank', 'Smith', 'Second street 2, Miami');
INSERT dbo.Customers VALUES (NULL, 'Joe', 'Johnson', 'Third Avenue 3, New York');
INSERT dbo.Orders VALUES (1, '2011-01-01', 30.02);
INSERT dbo.Orders VALUES (2, '2012-02-02', 15.99);
INSERT dbo.Orders VALUES (NULL, '2014-04-04', 107.00);
-- 073
SELECT *
FROM dbo.Customers c
INNER JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
-- 074
SELECT ISNULL(CustomerID, 99)
FROM dbo.Customers
-- 075
SELECT *
FROM dbo.Customers c
INNER JOIN dbo.Orders o ON ISNULL(c.CustomerID,99) = ISNULL(o.CustomerID,99)
-- 076
SELECT *
FROM dbo.Customers c
INNER JOIN dbo.Orders o ON (c.CustomerID IS NULL and o.CustomerID IS NULL)
OR c.CustomerID = o.CustomerID
-- 077
DROP TABLE dbo.Customers;
DROP TABLE dbo.Orders;
/* Implement functions and aggregate data */
-- 078
SELECT UPPER(FullName)
FROM [Application].[People]
-- 079
SELECT LOWER('ABCDE')
-- 080
SELECT UPPER(LOWER('ABCDE'))
-- 081
SELECT *
FROM [Application].[People]
WHERE LOWER(PreferredName) = 'isabelle'
-- 082
SELECT *
FROM fn_virtualfilestats(NULL,NULL);
-- 083
SELECT DB_ID('WideWorldImporters')
-- 084
SELECT DB_NAME(vfs.Dbid) as 'Database'
,mf.name as 'File name'
,mf.physical_name
,CASE NumberReads
WHEN 0 THEN 'none'
ELSE CAST(IoStallReadMS/NumberReads AS varchar(100))
END as 'Read latency'
,CASE NumberWrites
WHEN 0 THEN 'none'
ELSE CAST(IoStallWriteMS/NumberWrites AS varchar(100))
END as 'Write latency'
FROM fn_virtualfilestats(NULL,NULL) vfs
INNER JOIN sys.master_files mf ON vfs.DbId = mf.database_id AND vfs.Fileid = mf.file_id
ORDER BY DbId, file_id;
/* Identify the impact of function usage to query performance and WHERE clause sargability */
-- 085
SELECT PreferredName
FROM [Application].[People]
WHERE LEFT(PreferredName,3) = 'Isa'
SELECT PreferredName
FROM [Application].[People]
WHERE PreferredName LIKE 'Isa%'
/* index hint CREATE NONCLUSTERED INDEX [<Name of Missing Index, sysname,>] ON [Application].[People] ([PreferredName]) */
-- 086
CREATE NONCLUSTERED INDEX [NonClusteredIndex-PerformanceDemo] ON [Application].[People]
(
[PreferredName] ASC
)
GO
-- 087
DROP INDEX [NonClusteredIndex-PerformanceDemo] ON [Application].[People]
-- 088
SELECT DATEADD(week, 1, '2017-08-25')
-- 089
SELECT DATEADD(day, -1, GETDATE())
-- 090
CREATE NONCLUSTERED INDEX [NCIX-ExpectedDeliveryDate] ON [Sales].[Orders] ( [ExpectedDeliveryDate] ASC )
-- 091
SELECT OrderID
FROM Sales.Orders
WHERE ExpectedDeliveryDate = DATEADD(day, 1, GETDATE())
SELECT OrderID
FROM Sales.Orders
WHERE GETDATE() = DATEADD(day, -1, ExpectedDeliveryDate)
-- 092
DECLARE @tomorrow date
SET @tomorrow = DATEADD(day, 1, GETDATE())
SELECT OrderID
FROM Sales.Orders
WHERE ExpectedDeliveryDate = @tomorrow
-- 093
DROP INDEX [NCIX-ExpectedDeliveryDate] ON [Sales].[Orders]
/* Identify the differences between deterministic and non-deterministic functions */
-- 094
select RAND()
/* Use built-in aggregate functions */
-- 095
SELECT MAX(preferredname)
FROM Application.People
-- 096
SELECT TOP 1 PreferredName
FROM Application.People
ORDER BY PreferredName DESC
-- 097
SELECT count(*)
FROM sales.orders
-- 098
EXEC sp_spaceused 'sales.orders'
-- 099
SELECT SalespersonPersonID
,count(*) AS 'Orders per salesperson'
FROM sales.orders
GROUP BY SalespersonPersonID
ORDER BY SalespersonPersonID
-- 100
SELECT 'Average' = AVG(quantity)
,'Average #2' = AVG(CAST(quantity as decimal(5,2)))
,'Number' = COUNT(*)
,'Maximum' = MAX(quantity)
,'Minimum' = MIN(quantity)
,'Total' = SUM(quantity)
FROM Sales.Orderlines;
-- 101
SELECT cast(9310904 as dec(18,2))/cast(231412 as dec(18,2))
SELECT 9310904/231412
/* Use arithmetic functions, date-related functions, and system functions */
-- 102
SELECT 'Year' = YEAR('2017-08-26')
,'Year #2' = DATEPART(YEAR,'2017-08-26')
,'Month' = MONTH('2017-08-26')
,'Name of the month' = DATENAME(MONTH,'2017-08-26')
,'Day' = DAY('2017-08-26')
,'Name of the day' = DATENAME(WEEKDAY,'2017-08-26')
,'Day of the week' = DATEPART(WEEKDAY,'2017-08-26');
-- 103
SELECT @@DATEFIRST
-- 104
SET DATEFIRST 1;
SELECT 'First day of the week' = CASE @@DATEFIRST
WHEN 1 THEN 'Monday'
WHEN 2 THEN 'Tuesday'
WHEN 3 THEN 'Wednesday'
WHEN 4 THEN 'Thursday'
WHEN 5 THEN 'Friday'
WHEN 6 THEN 'Saturday'
WHEN 7 THEN 'Sunday'
ELSE 'I do not know what went wrong here'
END
SET DATEFIRST 7;
-- 105
SELECT 'Current time' = Current_Timestamp
,'Current time #2' = GETDATE()
,'Current time more precision' = Sysdatetime()
SELECT 'Current UTC time' = Getutcdate()
,'Current time more precision' = Sysutcdatetime()
,'Current time + UTC offset' = Sysdatetimeoffset()
-- 106
SELECT TODATETIMEOFFSET(GETDATE(), '+00:00')
-- 107
SELECT 'Moscow time' = SWITCHOFFSET (Sysdatetimeoffset(), '+03:00')
-- 108
SELECT ISDATE('2017-02-29')
-- 109
SELECT DATEDIFF(day,'1971-09-03', GETDATE())
/* arithmetic functions */
-- 110
SELECT ABS (7), ABS(-7)
-- 111
SELECT 7 % 3
-- 112
SELECT 'Floor' = FLOOR(12.345)
,'Ceiling' = CEILING(12.345)
,'Round to 100' = ROUND(12.345, -2)
,'Round to 10' = ROUND(12.345, -1)
,'Round to 1' = ROUND(12.345, 0)
,'Round to .1' = ROUND(12.345, 1)
,'Round to .01' = ROUND(12.345, 2)
/* string functions */
-- 113
SELECT CONCAT('mon', 'day')
-- 114
SELECT 'mon' + 'day'
-- 115
SELECT firstname + ' ' + lastname
FROM dbo.parent
SELECT CONCAT(firstname, ' ', lastname)
FROM dbo.parent
-- 116
SET CONCAT_NULL_YIELDS_NULL OFF
SELECT 'mon' + NULL + 'day'
SELECT CONCAT('mon', NULL, 'day')
SET CONCAT_NULL_YIELDS_NULL ON
SELECT 'mon' + NULL + 'day'
SELECT CONCAT('mon', NULL, 'day')
-- 117
SELECT LEFT('monday',3)
SELECT RIGHT('monday',3)
-- 118
SELECT SUBSTRING('The middle part', 5, 6)
-- 119
SELECT LEFT('monday', 3)
-- 120
SELECT SUBSTRING('monday', 1, 3)
-- 121
SELECT CHARINDEX('middle', 'the middle part')
-- 122
SELECT CHARINDEX('t', 'the middle part')
-- 123
SELECT CHARINDEX('t', 'the middle part', 2)
-- 124
SELECT PATINDEX('%m%e%', 'the middle part')
-- 125
SELECT REPLACE('the middle part', 'middle', 'best')
-- 126
SELECT LEN('the middle part')
-- 127
SELECT CHAR(65)
SELECT ASCII('A')
-- 128
DECLARE @strange_string VARCHAR(100)
SET @strange_string = 'mon' + CHAR(27) + 'day'
SELECT @strange_string
SELECT ASCII(SUBSTRING(@strange_string,4,1))
-- 129
BACKUP DATABASE model TO DISK = 'd:\model.bak'
-- 130
SELECT 'BACKUP DATABASE ' + name
FROM sys.databases
WHERE name <> 'tempdb'
-- 131
BACKUP DATABASE master
BACKUP DATABASE model
BACKUP DATABASE msdb
BACKUP DATABASE TestDB
BACKUP DATABASE WideWorldImporters
-- 132
SELECT 'BACKUP DATABASE ' + name + ' TO DISK = D:\' + name + '.bak'
-- 133
SELECT 'BACKUP DATABASE ' + name + ' TO DISK = ''D:\' + name + '.bak'''
-- 134
SELECT 'BACKUP DATABASE ' + name +
' TO DISK = ' + CHAR(39) + 'D:\' + name + '.bak' + CHAR(39)
-- 135
SELECT CONCAT('BACKUP DATABASE ', name,
' TO DISK = ', CHAR(39), 'D:\', name, '.bak', CHAR(39))
-- 136
SELECT REVERSE('monday')
/* system functions */
-- 136
SELECT HOST_NAME()
-- 137
SELECT USER_NAME()
-- 138
CREATE TABLE dbo.Employees
(
EmployeeID tinyint NOT NULL IDENTITY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
-- 139
INSERT dbo.Employees VALUES ('Jack', 'Ford', 'Second street 2, Denver');
-- 140
INSERT dbo.Employees VALUES (1, 'Jack', 'Ford', 'Second street 2, Denver');
-- 141
SET IDENTITY_INSERT dbo.Employees ON;
INSERT dbo.Employees (EmployeeID, FirstName, LastName, Address)
VALUES (1, 'Donald', 'Charleston', 'Times Square, New York');
SET IDENTITY_INSERT dbo.Employees OFF;
-- 142
INSERT dbo.Empolyees (FirstName, LastName, Address)
VALUES ('A.', 'Snowman' 'Mount Everest, Nepal');
SELECT @@IDENTITY
-- 143
DROP TABLE IF EXISTS dbo.Orders
DROP TABLE IF EXISTS dbo.OrderLines
CREATE TABLE dbo.Orders
(
OrderID tinyint NOT NULL IDENTITY PRIMARY KEY
,CustomerID tinyint NOT NULL
,OrderDate datetime NOT NULL
,SalesAmount decimal(18,2) NOT NULL
);
CREATE TABLE dbo.OrderLines
(
OrderLineID tinyint NOT NULL IDENTITY PRIMARY KEY
,OrderID tinyint NOT NULL
,Product varchar(100) NOT NULL
,Units tinyint NOT NULL
,UnitPrice decimal(18,2) NOT NULL
);
DECLARE @OrderID tinyint
INSERT dbo.Orders VALUES (1,'2015-05-05', 230.02);
SELECT @OrderID = @@IDENTITY
INSERT dbo.OrderLines VALUES ( @OrderID, 'ProductA', 1, 10.04);
-- 144
/*Old syntax to drop a table only if it exists*/
IF EXISTS ( SELECT name
FROM sys.tables
WHERE name = 'Orders'
and schema_id=SCHEMA_ID('dbo'))
DROP TABLE dbo.Orders
-- 145
SELECT IDENT_CURRENT('dbo.Orders')
-- 146
SELECT 'Globally unique identifier' = NEWID()
-- 147
CREATE TABLE tblGUID (
id uniqueidentifier DEFAULT NEWSEQUENTIALID()
,text varchar(100));
INSERT tblGUID (text) VALUES ('One')
INSERT tblGUID (text) VALUES ('Two')
INSERT tblGUID (text) VALUES ('Three')
SELECT *
FROM tblGUID
-- 148
SELECT ISNUMERIC('12') as Number
,ISNUMERIC(12) as Number
,ISNUMERIC('12A') as Number
-- 149
SELECT TRY_CAST('$20' as money)
SELECT TRY_CAST('$20' as int)
SELECT CAST('$20' as int)
-- 150
SELECT CAST('20170914' AS datetime)
,CONVERT(datetime, '20170914')
-- 151
SELECT CONVERT(varchar(100), GETDATE(), 100) AS 'Default'
,CONVERT(varchar(100), GETDATE(), 101) AS 'US'
,CONVERT(varchar(100), GETDATE(), 1) AS 'US (without century)'
,CONVERT(varchar(100), GETDATE(), 126) AS 'ISO8601'
,CONVERT(varchar(100), GETDATE(), 113) AS 'Europe default'
-- 152
SELECT *
FROM [Sales].[Invoices]
SELECT @@ROWCOUNT AS 'Number of records affected'
-- 153
SELECT *
FROM [Sales].[Invoices]
SELECT ROWCOUNT_BIG() AS 'Number of records affected'
/* Modify data */
-- 154
DROP IF EXISTS TABLE dbo.Employees
CREATE TABLE dbo.Employees
(
EmployeeID tinyint NOT NULL IDENTITY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
);
INSERT dbo.Customers VALUES ('Bob', 'Jackson', 'Main street 1, Dallas');
-- 155
INSERT dbo.Employees (FirstName, LastName)
VALUES ('Bob', 'Jackson')
INSERT dbo.Employees (FirstName, LastName, Address)
VALUES ('Bob', 'Jackson', NULL)
-- 156
CREATE TABLE dbo.Employees
(
EmployeeID tinyint NOT NULL IDENTITY
,FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL DEFAULT 'Under the bridge'
)
-- 157
ALTER TABLE dbo.Employees ADD DEFAULT ('Under the bridge') FOR [Address]
INSERT dbo.Employees (FirstName, LastName)
VALUES ('Bob', 'Jackson')
-- 158
INSERT dbo.Employees (FirstName, LastName)
VALUES ('Bob', 'Jackson')
INSERT dbo.Employees (FirstName, LastName, Address)
VALUES ('Bob', 'Jackson', DEFAULT)
-- 159
INSERT dbo.Employees DEFAULT VALUES
-- 160
INSERT dbo.Employees (FirstName, LastName)
VALUES ('Bob', 'Jackson')
,('Bo', 'Jackson')
,('Bill', 'Jackson')
-- 161
DROP TABLE IF EXISTS dbo.Employees_backup
CREATE TABLE dbo.Employees_backup
(
FirstName varchar(100) NOT NULL
,LastName varchar(100) NOT NULL
,[Address] varchar(100) NOT NULL
)
INSERT dbo.Employees_backup
SELECT FirstName, LastName, [Address]
FROM dbo.Employees
-- 162
INSERT dbo.Employees_backup
SELECT FirstName, LastName, [Address]
FROM dbo.Employees
UNION
SELECT 'Tim', 'Smith', 'Miami'
-- 163
DROP TABLE IF EXISTS dbo.Employees_backup
SELECT FirstName, LastName, [Address]
INTO dbo.Employees_backup
FROM dbo.Employees
-- 164
CREATE PROC dbo.usp_get_employees
AS
BEGIN
SELECT FirstName, LastName, Address FROM dbo.Employees
END
-- 165
EXEC usp_get_employees
-- 166
INSERT dbo.Employees_backup
EXEC usp_get_employees
-- 167
DECLARE @sql nvarchar(1000)
SET @sql = 'SELECT FirstName, LastName, Address FROM dbo.Employees'
EXEC (@sql)
-- 168
EXEC sp_executesql @statement = @sql
-- 169
INSERT dbo.Employees_backup
EXEC (@sql)
-- 170
INSERT dbo.Employees_backup
EXEC sp_executesql @statement = @sql
/* In more detail: dynamic SQL */
-- 171
SELECT TOP (3) *
FROM dbo.Employees
-- 172
SELECT TOP 50 percent *
FROM dbo.Employees
-- 173
SELECT TOP 50 percent *
FROM dbo.Employees
ORDER BY LastName
-- 174
DECLARE @sql varchar(1000)
,@top int
SET @top = 3
SET @sql = 'SELECT TOP ' + CAST (@top as varchar(10)) + 'FirstName, LastName, Address FROM dbo.Employees'
EXEC (@sql)
-- 175
-- create the table
CREATE TABLE Students (
FirstName varchar(100)
,LastName varchar(100))
INSERT INTO dbo.Students (FirstName, LastName) VALUES('Robert', 'Tables')
-- fetch the student record
DECLARE @sql nvarchar(1000)
,@Firstname nvarchar(1000)
SET @Firstname = 'Robert'
SET @sql = 'SELECT * FROM dbo.Students WHERE FirstName = ' + CHAR(39) + @Firstname + CHAR(39)
EXEC (@sql)
-- 176
SET @Firstname = 'Robert''; DROP TABLE dbo.Students--'
-- 177
SET @sql = 'SELECT * FROM dbo.Students WHERE FirstName = @FirstName'
EXECUTE sp_executesql
@statement = @sql
,@parameters = N'@FirstName as varchar(1000)'
,@FirstName = @FirstName
-- 178
DECLARE @sql nvarchar(1000)
,@top int
SET @sql = 'SELECT TOP (@top) FirstName, LastName, Address FROM dbo.Employees'
SET @top = 3
EXEC sp_executesql
@statement = @sql
,@parameters = N'@top as int'
,@top = @top
-- 179
SELECT TOP (@top) FirstName, LastName, Address
FROM dbo.Employees
/* Cursors */
-- 180
USE WideWorldImporters
DECLARE crsLoop CURSOR FOR
SELECT TOP (50) FullName, UserPreferences
FROM [Application].[People]
ORDER BY FullName
DECLARE @FullName nvarchar(50)
,@UserPreferences nvarchar(max)
OPEN crsLoop
FETCH NEXT FROM crsLoop INTO @FullName, @UserPreferences
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @FullName AS [Full Name], @UserPreferences AS [User Preferences]
FETCH NEXT FROM crsLoop INTO @FullName, @UserPreferences
END
CLOSE crsLoop
DEALLOCATE crsLoop
-- 181
SELECT @@SPID
-- 182
KILL 58
-- 183
SELECT *
FROM master..sysprocesses
WHERE dbid= DB_ID('TestDB')
-- 184
SELECT spid
FROM master..sysprocesses
WHERE dbid= DB_ID('TestDB')
GROUP BY spid
SELECT DISTINCT spid
FROM master..sysprocesses
WHERE dbid= DB_ID('TestDB')
-- 185
SELECT 'KILL ' + CAST(spid AS VARCHAR(10))
-- 186
DECLARE @SQL NVARCHAR(100);
DECLARE crsKill CURSOR LOCAL FAST_FORWARD
FOR SELECT 'KILL ' + CAST(spid AS VARCHAR(10))
FROM master.dbo.sysprocesses
WHERE dbid = DB_ID('TestDB')
GROUP BY spid;
OPEN crsKill;
FETCH crsKill INTO @SQL;
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_executesql @SQL;
FETCH crsKill INTO @SQL
END;
CLOSE crsKill;
DEALLOCATE crsKill;
/* update */
-- 187
UPDATE dbo.Employees
SET LastName = 'Didley'
WHERE FirstName = 'Bo'
-- 188
UPDATE TOP (1) dbo.Employees
SET LastName = 'Didley'
WHERE FirstName = 'Bo'
ORDER BY EmployeeID
-- 189
UPDATE dbo.Employees
SET LastName = 'Didley'
FROM ( SELECT TOP (1) EmployeeID
FROM dbo.Employees
WHERE FirstName = 'Bo'
ORDER BY EmployeeID) AS e
WHERE e.EmployeeID = Employees.EmployeeID
-- 190
UPDATE dbo.Employees
SET LastName = LTRIM(RTRIM(LastName))
,Address = DEFAULT
WHERE FirstName = 'Bo'
-- 191
UPDATE dbo.Employees
SET LastName = LTRIM(RTRIM(LastName))
,Address = 'Home of mr. ' + FirstName + ' ' + LastName
WHERE FirstName = 'Bo'
-- 192
ALTER TABLE dbo.Employees ADD Salary decimal(18,2) DEFAULT 1000.00
UPDATE dbo.Employees
SET Salary = DEFAULT
-- 193
UPDATE dbo.Employees
SET Salary = Salary + 100
WHERE FirstName = 'Bo'
UPDATE dbo.Employees
SET Salary += 100
WHERE FirstName = 'Bo'
-- 194
-- Bitwise comparison operators
SELECT 1 & 1 AS 'Two ones', 1 & 0 AS 'Left one', 0 & 1 AS 'Right one', 0 & 0 AS 'No one'
SELECT 1 | 1 AS 'Two ones', 1 | 0 AS 'Left one', 0 | 1 AS 'Right one', 0 | 0 AS 'No one'
SELECT 1 ^ 1 AS 'Two ones', 1 ^ 0 AS 'Left one', 0 ^ 1 AS 'Right one', 0 ^ 0 AS 'No one'
-- 195
SELECT 5 & 19, 5 | 19, 5 ^ 19
-- 196
-- Update on join
UPDATE c
SET c.StandardDiscountPercentage = 5
FROM sales.customers c
INNER JOIN sales.Orders o on c.CustomerID = o.CustomerID
WHERE o.OrderDate > '2016-01-01'
-- 197
UPDATE Sales.Customers
SET StandardDiscountPercentage = 0
WHERE StandardDiscountPercentage = 5
-- 198
-- Nondeterministic update on join
UPDATE o
SET comments = ol.Description
FROM sales.orders o
INNER JOIN sales.orderlines ol ON o.orderid = ol.orderid
WHERE o.OrderID = 46
-- 199
UPDATE Sales.Orders
SET comments = NULL
-- 200
-- Update WHERE CURRENT OF
DECLARE crsOrders CURSOR FOR
SELECT orderid
FROM Sales.orders
DECLARE @orderid int
OPEN crsOrders
FETCH NEXT FROM crsOrders INTO @orderid
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE Sales.Orders
SET Comments = 'This is order ' + CAST(@orderid AS VARCHAR(10))
WHERE CURRENT OF crsOrders
FETCH NEXT FROM crsOrders INTO @orderid
END
CLOSE crsOrders
DEALLOCATE crsOrders
-- 201
UPDATE Sales.Orders
SET Comments = 'This is order ' + CAST(OrderId as varchar(10))
-- 202
UPDATE Sales.Orders
SET comments = NULL
-- 203
DECLARE @Comments nvarchar(max)
UPDATE Sales.Orders
SET @Comments = Comments = 'This is order ' + CAST (OrderId as varchar(10))
WHERE OrderId = 1
SELECT @Comments
/* Delete */
-- 204
SELECT *
FROM sales.customers c
INNER JOIN sales.Orders o on c.CustomerID = o.CustomerID
WHERE o.OrderDate < '2010-01-01'
-- 205
DELETE
FROM c
FROM sales.customers c
INNER JOIN sales.Orders o on c.CustomerID = o.CustomerID
WHERE o.OrderDate < '2010-01-01'
-- 206
DECLARE @rowcount int;
SET @rowcount = 1;
WHILE @rowcount > 0
BEGIN
DELETE TOP (100000)
FROM dbo.MyVeryLargeTable;
SET @rowcount = @@rowcount;
WAITFOR DELAY '00:00:10';
END;
/* Output clause */
-- 207
DROP TABLE IF EXISTS output_test
CREATE TABLE output_test (id int, SomeText varchar(100))
INSERT output_test (id, SomeText) VALUES (1, 'before')
INSERT output_test (id, SomeText) VALUES (2, 'before')
UPDATE output_test
SET SomeText = 'after'
OUTPUT DELETED.*, INSERTED.*
DROP TABLE IF EXISTS output_test
-- 208
INSERT output_test (id, SomeText) OUTPUT INSERTED.* VALUES (2, 'before')
-- 209
INSERT output_test (id, SomeText) OUTPUT INSERTED.id VALUES (2, 'before')
-- 210
OUTPUT DELETED.* INTO output_test_before
-- 211
OUTPUT DELETED.id, DELETED.SomeText, GETDATE() INTO output_test_before (id, Sometext, ChangeTime)
/* Merge statement */
-- 212
DROP TABLE IF EXISTS Params_target
CREATE TABLE Params_target (drive CHAR(1), threshold_in_GB tinyint)
INSERT Params_target VALUES ('C',10), ('D',10), ('E',10), ('Q',10)
DECLARE @drive CHAR(1) = 'Q'
,@threshold_in_GB tinyint = 1
IF EXISTS (SELECT * FROM Params_target WHERE drive = @drive)
BEGIN
UPDATE Params_target
SET threshold_in_GB = @threshold_in_GB
WHERE drive = @drive
END
ELSE
BEGIN
INSERT Params_target VALUES(@drive, @threshold_in_GB)
END
-- 213
SELECT *
FROM Params_target
ORDER BY drive
-- 214
-- setup
DROP TABLE IF EXISTS Params_target
DROP TABLE IF EXISTS Params_source
CREATE TABLE Params_target (drive CHAR(1), threshold_in_GB tinyint)
INSERT Params_target VALUES ('C',10), ('D',10), ('E',10), ('Q',1)
CREATE TABLE Params_source (drive CHAR(1), threshold_in_GB tinyint)
INSERT Params_source VALUES('Q',1)
--actual MERGE statement
MERGE Params_target AS TARGET
USING Params_source AS SOURCE
ON TARGET.drive = SOURCE.drive
WHEN MATCHED AND SOURCE.threshold_in_GB <> TARGET.threshold_in_GB THEN
UPDATE SET threshold_in_GB = SOURCE.threshold_in_GB
WHEN NOT MATCHED BY TARGET THEN
INSERT (drive, threshold_in_GB) VALUES (SOURCE.drive, SOURCE.threshold_in_GB)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
OUTPUT $action, deleted.threshold_in_GB, inserted.threshold_in_GB;
/* Determine the results of Data Definition Language (DDL) statements on supplied tables and data */
-- 215
-- add column
ALTER TABLE [dbo].[Employees] ADD Department varchar(100) NULL
-- 216
ALTER TABLE [dbo].[Employees] DROP COLUMN Department
-- 217
ALTER TABLE [dbo].[Employees] ADD Department varchar(100) NOT NULL DEFAULT 'Sales'
Msg 5074, Level 16, State 1, Line 12
The object 'DF__Employees__Depar__2F5453E4' is dependent on column 'Department'.
Msg 4922, Level 16, State 9, Line 12
ALTER TABLE DROP COLUMN Department failed because one or more objects access this column.
-- 218
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [DF__Employees__Depar__2F5453E4]
-- 219
ALTER TABLE [dbo].[Employees] ADD Department varchar(100) NOT NULL
CONSTRAINT DF_Department DEFAULT 'Sales'
-- 220
ALTER TABLE [dbo].[Employees] ADD Department varchar(100) NULL
CONSTRAINT DF_Department DEFAULT 'Sales' WITH VALUES
-- 221
SELECT FirstName, LastName, Address, Salary
INTO Employees_test
FROM dbo.employees
ALTER TABLE [dbo].[Employees_test] ADD EmployeeID int IDENTITY
/* alter column */
-- 222
ALTER TABLE dbo.Employees ALTER COLUMN LastName int
-- 223
ALTER TABLE dbo.Employees ALTER COLUMN LastName varchar(5)
-- 224
ALTER TABLE dbo.Employees ALTER COLUMN LastName varchar(50)
-- 225
ALTER TABLE dbo.Employees ALTER COLUMN EmployeeId tinyint
-- 226
ALTER TABLE dbo.Employees ADD CONSTRAINT PK_Employeeid PRIMARY KEY (EmployeeId)
-- 227
CREATE TABLE Departments (Department varchar(100) NOT NULL PRIMARY KEY)
INSERT Departments VALUES ('Sales')
ALTER TABLE dbo.Employees ADD CONSTRAINT FK_Department FOREIGN KEY (Department) REFERENCES Departments(Department)
ALTER TABLE dbo.Employees ALTER COLUMN Department varchar(200)
-- 228
ALTER TABLE [dbo].[Employees] ADD EmployeeNumber int NULL
GO
UPDATE dbo.Employees SET EmployeeNumber = EmployeeID
ALTER TABLE [dbo].[Employees] ADD CONSTRAINT uq_employeenumber UNIQUE (EmployeeNumber)
GO
INSERT dbo.Employees (FirstName, LastName, Address, Salary, Department, EmployeeNumber)
VALUES('Lisa', 'Simpson','Springfield',1500.00,'Sales', NULL )
-- 229
ALTER TABLE [dbo].[Employees] DROP COLUMN EmployeeNumber
-- 230
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT uq_employeenumber
ALTER TABLE [dbo].[Employees] DROP COLUMN EmployeeNumber
-- 231
ALTER TABLE [dbo].[Employees] ADD EmployeeNumber int NULL
EXEC sp_rename 'Employees.EmployeeNumber', 'Employee_Number'
ALTER TABLE [dbo].[Employees] DROP COLUMN Employee_Number
/* drop column */
-- 232
ALTER TABLE [dbo].[Employees] DROP COLUMN Department
-- 233
CREATE INDEX ix_department ON dbo.Employees(Department)
ALTER TABLE [dbo].[Employees] DROP COLUMN Department
-- 234
DROP INDEX ix_lastname
-- 235
ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL