2. Agenda
Developer Features (which can be used in
SMARTBOOKS)
SQL Server 2012 -14
SSDT Tools
Programmability Enhancements: T-SQL Improvements
Programmability Enhancements: New T-SQL Functions
In-Memory OLTP Engine
SQL Server 2016
Drop if Exists (DIE)
Dynamic Data Masking (DDM)
Row level Security (RIS)
Always encrypted
Temporal Table
JSON Support
2
3. What is SSDT
New database Tooling in Visual Studio
SQL Server Management Studio (SSMS)
Visual studio Database Professional Edition (DbPro)
Not replacing SSMS
Replaces DbPro but not all
Model-Based Design
SSDT does not operates directly on database instead it is in-memory
representation of database structure from on-premesis datacenter, from local
Dev databases or Cloud databases.
It connects the development like SQL Server Object Explorer
New panel in side Visual Studio
New query window is provided as exists in SSMS
Power Buffer can edit object which exists in the memory and through this we
can validate the change and automatically generates and execute the script.
SSDT includes a lightweight single user instance of SQL Server for
development and testing.
SSDT does not support data manipulation like no data comparison or data
generation
3
4. Programmability Enhancements: T-SQL
Improvements
THROW statement
Before THROW the RAISEERROR was used to show the error.
But it requires user defined message and that message should
exists in sys.message table whereas THROW does not require
the error details exists in sys.messages. The THROW function
error number should be greater than 50000 and severity should
be 16
THROW 51000, 'The record does not exist.', 16;
RAISERROR statement THROW statement
If a msg_id is passed to RAISERROR,
the ID must be defined in
sys.messages.
The error_number parameter does not
have to be defined in sys.messages.
The severity parameter specifies the
severity of the exception.
There is no severity parameter. The
exception severity is always set to 16.
4
5. Programmability Enhancements: T-SQL
Improvements cont…
Built-in pagination
Before SQL Server 2012 we were using row_number function for
the pagination which was handle manually by the developers as
shown below
;WITH PageNumbers AS(
Select id, OrderNumber, row_number() over (order by ordernumber
desc) rn
from orders
)
SELECT *
FROM PageNumbers
WHERE rn BETWEEN 301 AND 310
SELECT id, OrderNumber
FROM dbo.orders
ORDER BY OrderNumber desc
OFFSET 300 ROWS
FETCH NEXT 10 ROWS ONLY;
5
6. Programmability Enhancements: T-SQL
Improvements cont….
Sequences
-- Create a simple sequence:
CREATE SEQUENCE dbo.ExampleSequence AS int
START WITH 1 INCREMENT BY 1;
-- Create a simple/test table, too:
CREATE TABLE dbo.SequentialTable (
SampleId int NOT NULL,
SampleValue nvarchar(40) NOT NULL
);
-- Sample/example of easiest way to grab value:
SELECT NEXT VALUE FOR dbo.ExampleSequence;
-- Now copy 'next' value (2) into a parameter:
DECLARE @NextSequence int
SELECT @NextSequence = NEXT VALUE
FOR dbo.ExampleSequence;
-- And use it for an INSERT.
-- But in non-trivial examples - you could use it for FK inserts
-- or other operations as well BEFORE trying the following INSERT.
INSERT INTO dbo.SequentialTable (SampleId, SampleValue)
VALUES (@NextSequence, '@NextSequence will have a value of 2.');
SELECT * FROM dbo.SequentialTable;
GO
6
7. Programmability Enhancements: T-SQL
Improvements cont…
Projection redirection and the WITH RESULT SETS
argument.
-- simple sample sproc:
CREATE PROC dbo.TestProc
@input1 int,
@input2 varchar(20)
AS
SET NOCOUNT ON
SELECT @input1 AS [Output1], @input2 [Output2]
RETURN 0
GO
-- Now transform the output/projection/results:
EXEC dbo.TestProc 292, 'This is Some Text'
WITH RESULT SETS ( ([Column 1] int, [Column 2] varchar(20)) );
7
8. Programmability Enhancements: New T-SQL
Functions
FORMAT().
SELECT
FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date],
FORMAT(GETDATE(), 'yyyy-MM-dd hh:mm:ss') AS [Full ISO],
FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-hand Date (EN)],
FORMAT(GETDATE(), 'MMMM dd, yyyy', 'fr-FR') AS [French Date],
FORMAT(22.7, 'C', 'en-US') AS [US Currency],
FORMAT(22.7, 'C', 'en-GB') AS [UK Currency],
FORMAT(99 * 2.226, '000.000') AS [Padded Decimal],
FORMAT(12345678, '0,0') AS [Finally: Commas in Large Numbers;
CHOOSE().
-- CHOOSE() makes these easy to 'format' in ad hoc
-- reports. The following returns 'Male' or position
-- number 2 in the 1-based (i.e., non-0 based) array.
SELECT CHOOSE(2, 'Female','Male', 'Unknown')
AS [Gender];
-- Just be aware that hard-coding values into
-- 'permanent' code can/will cause problems long term.
-- The following returns NULL - as 4 exceeds array or is not found.
SELECT CHOOSE(4,'Female','Male','Unknown') AS [x];
IIF
DECLARE @P INT = NULL, @S INT = NULL;
SELECT IIF ( 45 > 30, @p, @s ) AS Result;2.
Concat
Select Concat (‘Smart’, ‘ ’, ‘Books’, NULL, ‘Version’ ,5)
8
9. In-Memory OLTP Engine
It has mainly features two new data structures which are Memory-Optimized
Tables, and Natively-Compiled Stored Procedures.
Memory-optimized tables
The main features of memory-optimized tables are:
Rows in the table are read from, and written to, memory
The entire table resides in memory
Non-blocking multi-version optimistic concurrency control
The option of durable & non-durable data
A second copy is maintained on disk for durability (if enabled)
Data in memory-optimized tables is only read from disk during database recovery
It is interoperable with disk-based tables
Natively-compiled stored procedures
It is compiled to native code (DLL) upon its creation (the interpreted stored
procedures are compiled at first execution)
Aggressive optimizations take time at compile time
It can only interact with memory-optimized tables
The call to a natively-compiled stored procedure is actually a call to its DLL entry
point
9
10. In-Memory OLTP Engine
ALTER DATABASE AdventureWorks2012
ADD FILEGROUP INMOLTP_fg CONTAINS MEMORY_OPTIMIZED_DATA;
GO
ALTER DATABASE AdventureWorks2012
ADD FILE (NAME='INMOLTP_fg', FILENAME='c:tempINMOLTP_fg')
TO FILEGROUP INMOLTP_fg;
GO
--Memory-Optimized Table: Durable / Specifying a *_BIN2 Collation
CREATE TABLE [dbo].[Product]
(
ID INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 1000),
Code VARCHAR(10) COLLATE Latinl_General_100_BIN2 NOT NULL,
Description VARCHAR(200) NOT NULL,
Price FLOAT NOT NULL
)WITH (MEMORY_OPTIMIZED = ON,
DURABILITY = SCHEMA_ONLY);
GO
The corresponding non-durable memory-optimized table for “Product” would be defined as below:
--Disk-Based Table
CREATE TABLE [dbo].[Product]
(
ID INT NOT NULL PRIMARY KEY,
Code VARCHAR(10) NOT NULL ,
Description VARCHAR(200) NOT NULL ,
Price FLOAT NOT NULL
);
GO
10
11. In-Memory OLTP Engine
--Memory-Optimized Table: Durable / Specifying a *_BIN2 Collation
CREATE TABLE [dbo].[Product]
(
ID INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 1000),
Code VARCHAR(10) NOT NULL,
Description VARCHAR(200) NOT NULL,
Price FLOAT NOT NULL
)WITH (MEMORY_OPTIMIZED = ON,
DURABILITY = SCHEMA_AND_DATA);
GO
Also, the corresponding durable memory-optimized table for “Product” would be defined as below, having as the
only difference from the previous one the value “SCHEMA_AND_DATA” for the Durability setting:
11
12. In-Memory OLTP Engine
--Natively Compiled Stored Procedure for Product Table Update
CREATE PROCEDURE [dbo].[spProductUpdate]
WITH NATIVE_COMPILATION,
SCHEMABINDING,
EXECUTE AS OWNER
AS
BEGIN ATOMIC WITH ( TRANSACTION ISOLATION LEVEL = SNAPSHOT,
LANGUAGE = N'us_english' )
UPDATE dbo.Product
SET Price = Price - ( Price * 0.10 );
END;
Natively-compiled stored procedures.
12
13. Common Table Expressions (CTE)
13
;WITH ProductsCTE(ProdName,Price) AS (
SELECT ProductDesc,Price FROM PRODUCTS WHERE
Price>20.00
)
SELECT * FROM ProductsCTE
DECLARE @T INT,@I INT SET @T = 10 SET @I = 20 ;WITH
ProductsCTE(ProdName,Price) AS ( SELECT
ProductDesc,Price FROM PRODUCTS WHERE Price>20.00 )
SELECT @T+@I
SELECT * FROM ProductsCTE
Msg 422, Level 16, State 4, Line 10
Common table expression defined but not used.
15. 15
;WITH ProductsCTE(ProdName,Price) AS ( SELECT
ProductDesc,Price FROM PRODUCTS WHERE
Price>20.00 )
UPDATE ProductsCTE SET Price=50 WHERE
ProdName='Milk' SELECT * FROM ProductsCTE
;WITH StudCTE(RollNo,StudentName,TeacherID)
AS ( SELECT ID,Name,TID FROM Student )
,TeacherCTE(TID,TeacherName)
AS ( SELECT ID,Name FROM Teacher )
SELECT RollNo,StudentName,TeacherName
FROM StudCTE SC
INNER JOIN TeacherCTE TC ON SC.TeacherID=TC.TID
16. Recursion in CTE
16
DECLARE @T VARCHAR(100)='Where,there,is,a,will,there,is,a,way' SET @T =@T+','
;WITH MyCTE(Start,[End]) AS(
SELECT 1 AS Start,CHARINDEX(',',@T,1) AS [End]
UNION ALL
SELECT [End]+1 AS Start,CHARINDEX(',',@T,[End]+1)AS [End] from MyCTE where
[End]<LEN(@T) )
Select SUBSTRING(@T,Start,[End]-Start)from MyCTE;
The OPTION MAXRECURSION enables the code to recurse only once and
terminates as soon as that happens.The self explanatory message flashes and
the values returned out on the results pane is:
DECLARE @T VARCHAR(100)='Where,there,is,a,will,there,is,a,way'
SET @T =@T+','
;WITH MyCTE(Start,[End]) AS(
SELECT 1 AS Start,CHARINDEX(',',@T,1) AS [End]
UNION ALL
SELECT [End]+1 AS Start,CHARINDEX(',',@T,[End]+1)AS [End] from MyCTE
where [End]<LEN(@T)
)
Select Start,[End],SUBSTRING(@T,Start,[End]-Start)AS String from MyCTE
OPTION (MAXRECURSION 1);
17. 17
--create sequence orderids as int --minvalue 1 --cycle; --select next value for orderids; --
select next value for orderids;
create table MyOrders(
orderid INT NOT NULL PRIMARY KEY,
custid INT NOT NULL,
empid INT NOT NULL,
orderdate DATE NOT NULL )
DECLARE @Orders AS TABLE(
orderid INT NOT NULL PRIMARY KEY,
custid INT NOT NULL, empid INT NOT NULL,
orderdate DATE NOT NULL, shipcountry varchar(100) );
INSERT INTO @Orders(orderid, custid, empid, orderdate,shipcountry)
VALUES (2, 1, 3, '20120612','Norway'),
(3, 2, 2, '20120612','Norway'),
(4, 3, 5, '20120612',‘USA');
-- CTE for filtering rows -- CTE for filtering rows -- CTE for filtering rows
WITH SRC AS (
SELECT * FROM @Orders WHERE shipcountry = N'Norway'
)
MERGE INTO MyOrders AS TGT
USING SRC ON SRC.orderid = TGT.orderid
WHEN MATCHED AND ( TGT.custid <> SRC.custid OR TGT.empid <> SRC.empid OR
TGT.orderdate <> SRC.orderdate)
THEN UPDATE SET TGT.custid = SRC.custid, TGT.empid = SRC.empid, TGT.orderdate =
SRC.orderdate
WHEN NOT MATCHED THEN INSERT VALUES(SRC.orderid, SRC.custid, SRC.empid,
SRC.orderdate); select * from MyOrders
18. SQL Server 2016 Drop if Exits (DIE)
Drop if Exits (DIE)
After SQL Server 2016 you can use new DIE statements instead of big IF wrappers, e.g.:
Before SQL Server 2016
IF EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'<Schema
Name>.<Procedure Name>') AND TYPE IN (N'P', N'PC'))
BEGIN
Drop Procedure <Schema Name>.<Procedure Name>')
END
After SQL Server 2016
DROP TABLE IF EXISTS '<Schema Name>.<Table Name>')
DROP Procedure IF EXISTS '<Schema Name>.<Procedure Name>')
18
20. SQL Server 2016 Dynamic Data Masking
Dynamic data masking helps prevent unauthorized access to
sensitive data by enabling customers to designate how much of
the sensitive data to reveal with minimal impact on the application
layer.
20
22. SQL Server 2016 Row Level Security
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. For example ensuring that workers
can access only those data rows that are pertinent to their
department, or restricting a customer's data access to only the data
relevant to their company.
22
24. SQL Server 2016 Always Encrypted
Always Encrypted is a feature designed to protect sensitive data, such as credit card
numbers or national identification numbers (e.g. U.S. social security numbers), stored
in Azure SQL Database or SQL Server databases. Always Encrypted allows clients to
encrypt sensitive data inside client applications and never reveal the encryption keys to
the Database Engine (SQL Database or SQL Server).
24
25. SQL Server 2016 Temporal Table
A temporal table is table that holds old versions of rows within a
base table.
25
26. SQL Server 2016 JSON Support
JSON stands for Java Script Object Notation. With SQL Server 2016
you can now interchange JSON data between applications and the
SQL Server database engine.
26
With the release of SQL Server 2012 a new tool SSDT is released. SSDT is integrated development environment for SQL Server for desiging, Testing and deployment for SQL server database. It provide the tools like SSMS in VS 2012 and later for the database desiging in Visual Studio.
Even as SQL Server 2012's improved tooling and enhanced IDEs for developers to improve productivity, SQL Server 2012 also sports a number of programmability enhancements and functions that SQL Server developers will enjoy. SQL Server 2012 packs in a number of great features and capabilities that developers have been requesting for a while now, along with some great surprises that provide some useful new capabilities. Let's take a look at the new programmability features.