napkin-0.5.14
Safe HaskellSafe-Inferred
LanguageGHC2021

Napkin.Backends.MsSql.ApiGen

Description

Module exposes Sql Server API as Haskell functions for SExp generated out of MSDN specs.

Synopsis

Documentation

msCount_STAR :: SExp #

Origin documentation for msCount_STAR

Syntax:

COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msCount_Distinctness #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msCount_Distinctness

Syntax:

COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msCount :: SExp #

Origin documentation for msCount

Syntax:

COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msCast_Length #

Arguments

:: SExp 
-> SExp 
-> SExp

length'

-> SExp 

Origin documentation for msCast_Length

Syntax:

CAST ( expression AS data_type [ ( length ) ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msCast #

Arguments

:: SExp 
-> SExp

dataType

-> SExp 

Origin documentation for msCast

Syntax:

CAST ( expression AS data_type [ ( length ) ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msConvert_Length_Style #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

style

-> SExp 

Origin documentation for msConvert_Length_Style

Syntax:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msConvert_Length #

Arguments

:: SExp 
-> SExp 
-> SExp

expression

-> SExp 

Origin documentation for msConvert_Length

Syntax:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msConvert_Style #

Arguments

:: SExp 
-> SExp 
-> SExp

style

-> SExp 

Origin documentation for msConvert_Style

Syntax:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msConvert #

Arguments

:: SExp 
-> SExp

expression

-> SExp 

Origin documentation for msConvert

Syntax:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

No description

Example:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary);

Example:

SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS;

Example:

DECLARE @myval DECIMAL(5, 2);
SET @myval = 193.57;

SELECT CAST(CAST(@myval AS VARBINARY(20)) AS DECIMAL(10, 5));

-- Or, using CONVERT
SELECT CONVERT(DECIMAL(10, 5), CONVERT(VARBINARY(20), @myval));
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    SUBSTRING(p.Title, 1, 25) AS Title,
    CAST(e.SickLeaveHours AS CHAR(1)) AS [Sick Leave]
FROM HumanResources.Employee e
INNER JOIN Person.Person p
    ON e.BusinessEntityID = p.BusinessEntityID
WHERE NOT e.BusinessEntityID > 5;
GO

Example:

SELECT CAST(10.6496 AS INT) AS trunc1,
       CAST(-10.6496 AS INT) AS trunc2,
       CAST(10.6496 AS NUMERIC) AS round1,
       CAST(-10.6496 AS NUMERIC) AS round2;

Example:

SELECT CAST(10.3496847 AS money);

Example:

DECLARE @x NVARCHAR(10) = 'ab' + NCHAR(0x10000);

SELECT CAST(@x AS NVARCHAR(3));

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CAST(ListPrice AS INT) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT SUBSTRING(Name, 1, 30) AS ProductName,
    ListPrice
FROM Production.Product
WHERE CONVERT(INT, ListPrice) LIKE '33%';
GO

Example:

USE AdventureWorks2019;
GO

SELECT CAST(ROUND(SalesYTD / CommissionPCT, 0) AS INT) AS Computed
FROM Sales.SalesPerson
WHERE CommissionPCT != 0;
GO

Example:

SELECT 'The list price is ' + CAST(ListPrice AS VARCHAR(12)) AS ListPrice
FROM dbo.DimProduct
WHERE ListPrice BETWEEN 350.00 AND 400.00;

Example:

SELECT DISTINCT CAST(EnglishProductName AS CHAR(10)) AS Name,
    ListPrice
FROM dbo.DimProduct
WHERE EnglishProductName LIKE 'Long-Sleeve Logo Jersey, M';
GO

Example:

USE AdventureWorks2019;
GO

SELECT p.FirstName,
    p.LastName,
    s.SalesYTD,
    s.BusinessEntityID
FROM Person.Person AS p
INNER JOIN Sales.SalesPerson AS s
    ON p.BusinessEntityID = s.BusinessEntityID
WHERE CAST(CAST(s.SalesYTD AS INT) AS CHAR(20)) LIKE '2%';
GO

Example:

SELECT CONVERT(XML, '<root><child/></root>')

Example:

SELECT CONVERT(XML, '<root>          <child/>         </root>', 1)

Example:

SELECT CAST('<Name><FName>Carol</FName><LName>Elliot</LName></Name>'  AS XML)

Example:

SELECT GETDATE() AS UnconvertedDateTime,
    CAST(GETDATE() AS NVARCHAR(30)) AS UsingCast,
    CONVERT(NVARCHAR(30), GETDATE(), 126) AS UsingConvertTo_ISO8601;
GO

Example:

SELECT '2006-04-25T15:50:59.997' AS UnconvertedText,
    CAST('2006-04-25T15:50:59.997' AS DATETIME) AS UsingCast,
    CONVERT(DATETIME, '2006-04-25T15:50:59.997', 126) AS UsingConvertFrom_ISO8601;
GO

Example:

--Convert the binary value 0x4E616d65 to a character value.
SELECT CONVERT(CHAR(8), 0x4E616d65, 0) AS [Style 0, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 1) AS [Style 1, binary to character];

Example:

SELECT CONVERT(CHAR(8), 0x4E616d65, 2) AS [Style 2, binary to character];

Example:

SELECT CONVERT(BINARY(8), 'Name', 0) AS [Style 0, character to binary];

Example:

SELECT CONVERT(BINARY(4), '0x4E616D65', 1) AS [Style 1, character to binary];

Example:

SELECT CONVERT(BINARY(4), '4E616D65', 2) AS [Style 2, character to binary];

Example:

DECLARE @d1 DATE,
    @t1 TIME,
    @dt1 DATETIME;

SET @d1 = GETDATE();
SET @t1 = GETDATE();
SET @dt1 = GETDATE();
SET @d1 = GETDATE();

-- When converting date to datetime the minutes portion becomes zero.
SELECT @d1 AS [DATE],
    CAST(@d1 AS DATETIME) AS [date as datetime];

-- When converting time to datetime the date portion becomes zero
-- which converts to January 1, 1900.
SELECT @t1 AS [TIME],
    CAST(@t1 AS DATETIME) AS [time as datetime];

-- When converting datetime to date or time non-applicable portion is dropped.
SELECT @dt1 AS [DATETIME],
    CAST(@dt1 AS DATE) AS [datetime as date],
    CAST(@dt1 AS TIME) AS [datetime as time];

Example:

DECLARE @d1 DATE, @dt1 DATETIME , @dt2 DATETIME2

SET @d1 = '1492-08-03'
--This is okay; Minimum YYYY for DATE is 0001

SET @dt2 = CAST(@d1 AS DATETIME2)
--This is okay; Minimum YYYY for DATETIME2 IS 0001

SET @dt1 = CAST(@d1 AS DATETIME)
--This will error with (Msg 242) "The conversion of a date data type to a datetime data type resulted in an out-of-range value."
--Minimum YYYY for DATETIME is 1753

Example:

DECLARE @string VARCHAR(10);
SET @string = 1;
SELECT @string + ' is a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + ' is not a string.' AS Result

Example:

DECLARE @notastring INT;
SET @notastring = '1';
SELECT @notastring + '1'

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CAST(ListPrice AS int) LIKE '3%';

Example:

SELECT EnglishProductName AS ProductName, ListPrice
FROM dbo.DimProduct
WHERE CONVERT(INT, ListPrice) LIKE '3%';

Example:

SELECT ProductKey, UnitPrice,UnitPriceDiscountPct,
       CAST(ROUND (UnitPrice*UnitPriceDiscountPct,0) AS int) AS DiscountPrice
FROM dbo.FactResellerSales
WHERE SalesOrderNumber = 'SO47355'
      AND UnitPriceDiscountPct > .02;

Example:

SELECT EnglishProductName AS Name, ListPrice
FROM dbo.DimProduct
WHERE CAST(CAST(ListPrice AS INT) AS CHAR(20)) LIKE '2%';

Example:

SELECT TOP(1)
   SYSDATETIME() AS UnconvertedDateTime,
   CAST(SYSDATETIME() AS NVARCHAR(30)) AS UsingCast,
   CONVERT(NVARCHAR(30), SYSDATETIME(), 126) AS UsingConvertTo_ISO8601
FROM dbo.DimCustomer;

Example:

SELECT TOP(1)
   '2010-07-25T13:50:38.544' AS UnconvertedText,
CAST('2010-07-25T13:50:38.544' AS DATETIME) AS UsingCast,
   CONVERT(DATETIME, '2010-07-25T13:50:38.544', 126) AS UsingConvertFrom_ISO8601
FROM dbo.DimCustomer;

msConcat #

Arguments

:: SExp 
-> NonEmpty SExp

stringValue2

-> SExp 

Origin documentation for msConcat

Syntax:

CONCAT ( string_value1, string_value2 [, string_valueN ] )

This function returns a string resulting from the concatenation, or joining, of two or more string values in an end-to-end manner. (To add a separating value during concatenation, see CONCAT_WS .)

Example:

SELECT CONCAT ( 'Happy ', 'Birthday ', 11, '/', '25' ) AS Result;

Example:

CREATE TABLE #temp (
    emp_name NVARCHAR(200) NOT NULL,
    emp_middlename NVARCHAR(200) NULL,
    emp_lastname NVARCHAR(200) NOT NULL
);
INSERT INTO #temp VALUES( 'Name', NULL, 'Lastname' );
SELECT CONCAT( emp_name, emp_middlename, emp_lastname ) AS Result
FROM #temp;

msSum #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msSum

Syntax:

-- Aggregate Function Syntax
SUM ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
SUM ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

Example:

SELECT Color, SUM(ListPrice), SUM(StandardCost)
FROM Production.Product
WHERE Color IS NOT NULL
    AND ListPrice != 0.00
    AND Name LIKE 'Mountain%'
GROUP BY Color
ORDER BY Color;
GO

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                           ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY TerritoryID,SalesYear;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY SalesYear;

Example:

-- Uses AdventureWorks

SELECT ProductKey, SUM(SalesAmount) AS TotalPerProduct
FROM dbo.FactInternetSales
WHERE OrderDateKey >= '20030101'
      AND OrderDateKey < '20040101'
GROUP BY ProductKey
ORDER BY ProductKey;

Example:

-- Uses AdventureWorks

SELECT Color, SUM(ListPrice)AS TotalList,
       SUM(StandardCost) AS TotalCost
FROM dbo.DimProduct
GROUP BY Color
ORDER BY Color;

msVar #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msVar

Syntax:

-- Aggregate Function Syntax
VAR ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VAR ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance of all values in the specified expression. May be followed by the OVER clause .

Example:

SELECT VAR(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VAR(DISTINCT SalesAmountQuota)AS Distinct_Values, VAR(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VAR(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msMax #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msMax

Syntax:

-- Aggregation Function Syntax
MAX( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MAX ([ ALL ] expression) OVER ( <partition_by_clause> [ <order_by_clause> ] )

Returns the maximum value in the expression.

Example:

SELECT MAX(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

SELECT MAX(name) FROM sys.databases WHERE database_id < 5;

msAvg_OVER #

Arguments

:: Maybe Distinctness 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msAvg_OVER

Syntax:

AVG ( [ ALL | DISTINCT ] expression )
   [ OVER ( [ partition_by_clause ] order_by_clause ) ]

This function returns the average of the values in a group. It ignores null values.

Example:

SELECT AVG(VacationHours)AS 'Average vacation hours',
    SUM(SickLeaveHours) AS 'Total sick leave hours'
FROM HumanResources.Employee
WHERE JobTitle LIKE 'Vice President%';

Example:

SELECT TerritoryID, AVG(Bonus)as 'Average bonus', SUM(SalesYTD) as 'YTD sales'
FROM Sales.SalesPerson
GROUP BY TerritoryID;
GO

Example:

SELECT AVG(DISTINCT ListPrice)
FROM Production.Product;

Example:

SELECT AVG(ListPrice)
FROM Production.Product;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                           ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY TerritoryID,SalesYear;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY SalesYear;

msAvg #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msAvg

Syntax:

AVG ( [ ALL | DISTINCT ] expression )
   [ OVER ( [ partition_by_clause ] order_by_clause ) ]

This function returns the average of the values in a group. It ignores null values.

Example:

SELECT AVG(VacationHours)AS 'Average vacation hours',
    SUM(SickLeaveHours) AS 'Total sick leave hours'
FROM HumanResources.Employee
WHERE JobTitle LIKE 'Vice President%';

Example:

SELECT TerritoryID, AVG(Bonus)as 'Average bonus', SUM(SalesYTD) as 'YTD sales'
FROM Sales.SalesPerson
GROUP BY TerritoryID;
GO

Example:

SELECT AVG(DISTINCT ListPrice)
FROM Production.Product;

Example:

SELECT AVG(ListPrice)
FROM Production.Product;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                           ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY TerritoryID,SalesYear;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY SalesYear;

msIsNull #

Arguments

:: SExp 
-> SExp

replacementValue

-> SExp 

Origin documentation for msIsNull

Syntax:

ISNULL ( check_expression , replacement_value )

Replaces NULL with the specified replacement value.

Example:

USE AdventureWorks2012;
GO
SELECT AVG(ISNULL(Weight, 50))
FROM Production.Product;
GO

Example:

USE AdventureWorks2012;
GO
SELECT Description, DiscountPct, MinQty, ISNULL(MaxQty, 0.00) AS 'Max Quantity'
FROM Sales.SpecialOffer;
GO

Example:

USE AdventureWorks2012;
GO
SELECT Name, Weight
FROM Production.Product
WHERE Weight IS NULL;
GO

Example:

-- Uses AdventureWorks

SELECT AVG(ISNULL(Weight, 50))
FROM dbo.DimProduct;

Example:

-- Uses AdventureWorks

SELECT ResellerName,
       ISNULL(MinPaymentAmount,0) AS MinimumPayment
FROM dbo.DimReseller
ORDER BY ResellerName;

Example:

-- Uses AdventureWorks

SELECT EnglishProductName, Weight
FROM dbo.DimProduct
WHERE Weight IS NULL;

msSign #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for msSign

Syntax:

SIGN ( numeric_expression )

Returns the positive (+1), zero (0), or negative (-1) sign of the specified expression.

Example:

DECLARE @value REAL
SET @value = -1
WHILE @value < 2
   BEGIN
      SELECT SIGN(@value)
      SET NOCOUNT ON
      SELECT @value = @value + 1
      SET NOCOUNT OFF
   END
SET NOCOUNT OFF
GO

Example:

SELECT SIGN(-125), SIGN(0), SIGN(564);

msAbs #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for msAbs

Syntax:

ABS ( numeric_expression )

A mathematical function that returns the absolute (positive) value of the specified numeric expression. ( ABS changes negative values to positive values. ABS has no effect on zero or positive values.)

Example:

SELECT ABS(-1.0), ABS(0.0), ABS(1.0);

Example:

---- ---- ----
1.0  .0   1.0

Example:

DECLARE @i INT;
SET @i = -2147483648;
SELECT ABS(@i);
GO

msMin #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for msMin

Syntax:

-- Aggregation Function Syntax
MIN ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MIN ( [ ALL ] expression ) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] )

Returns the minimum value in the expression. May be followed by the OVER clause .

Example:

SELECT MIN(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice)
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664');

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice) OVER(PARTITION BY SalesOrderNumber) AS LeastExpensiveProduct,
       SalesOrderNumber
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664')
ORDER BY SalesOrderNumber;

keyName_KeyGuid #

Arguments

:: SExp

keyGuid'

-> SExp 

Origin documentation for keyName_KeyGuid

Syntax:

KEY_NAME ( ciphertext | key_guid )

Returns the name of the symmetric key from either a symmetric key GUID or cipher text.

Example:

USE master;
GO
DECLARE @guid uniqueidentifier ;
SELECT @guid = key_guid FROM sys.symmetric_keys
WHERE name = '##MS_ServiceMasterKey##' ;
-- Demonstration of passing a GUID to KEY_NAME to receive a name
SELECT KEY_NAME(@guid) AS [Name of Key];

Example:

-- Create a symmetric key
CREATE SYMMETRIC KEY TestSymKey
   WITH ALGORITHM = AES_128,
   KEY_SOURCE = 'The square of the hypotenuse is equal to the sum of the squares of the sides',
   IDENTITY_VALUE = 'Pythagoras'
   ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y' ;
GO
-- Create a table for the demonstration
CREATE TABLE DemoKey
(IDCol INT IDENTITY PRIMARY KEY,
SecretCol VARBINARY(256) NOT NULL)
GO
-- Open the symmetric key if not already open
OPEN SYMMETRIC KEY TestSymKey
    DECRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y';
GO
-- Insert a row into the DemoKey table
DECLARE @key_GUID uniqueidentifier;
SELECT @key_GUID = key_guid FROM sys.symmetric_keys
WHERE name LIKE 'TestSymKey' ;
INSERT INTO DemoKey(SecretCol)
VALUES ( ENCRYPTBYKEY (@key_GUID, 'EncryptedText'))
GO
-- Verify the DemoKey data
SELECT * FROM DemoKey;
GO
-- Decrypt the data
DECLARE @ciphertext VARBINARY(256);
SELECT @ciphertext = SecretCol
FROM DemoKey WHERE IDCol = 1 ;
SELECT CAST (
DECRYPTBYKEY( @ciphertext)
AS VARCHAR(100) ) AS SecretText ;
-- Use KEY_NAME to view the name of the key
SELECT KEY_NAME(@ciphertext) AS [Name of Key] ;

keyName_Ciphertext #

Arguments

:: SExp

ciphertext

-> SExp 

Origin documentation for keyName_Ciphertext

Syntax:

KEY_NAME ( ciphertext | key_guid )

Returns the name of the symmetric key from either a symmetric key GUID or cipher text.

Example:

USE master;
GO
DECLARE @guid uniqueidentifier ;
SELECT @guid = key_guid FROM sys.symmetric_keys
WHERE name = '##MS_ServiceMasterKey##' ;
-- Demonstration of passing a GUID to KEY_NAME to receive a name
SELECT KEY_NAME(@guid) AS [Name of Key];

Example:

-- Create a symmetric key
CREATE SYMMETRIC KEY TestSymKey
   WITH ALGORITHM = AES_128,
   KEY_SOURCE = 'The square of the hypotenuse is equal to the sum of the squares of the sides',
   IDENTITY_VALUE = 'Pythagoras'
   ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y' ;
GO
-- Create a table for the demonstration
CREATE TABLE DemoKey
(IDCol INT IDENTITY PRIMARY KEY,
SecretCol VARBINARY(256) NOT NULL)
GO
-- Open the symmetric key if not already open
OPEN SYMMETRIC KEY TestSymKey
    DECRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y';
GO
-- Insert a row into the DemoKey table
DECLARE @key_GUID uniqueidentifier;
SELECT @key_GUID = key_guid FROM sys.symmetric_keys
WHERE name LIKE 'TestSymKey' ;
INSERT INTO DemoKey(SecretCol)
VALUES ( ENCRYPTBYKEY (@key_GUID, 'EncryptedText'))
GO
-- Verify the DemoKey data
SELECT * FROM DemoKey;
GO
-- Decrypt the data
DECLARE @ciphertext VARBINARY(256);
SELECT @ciphertext = SecretCol
FROM DemoKey WHERE IDCol = 1 ;
SELECT CAST (
DECRYPTBYKEY( @ciphertext)
AS VARCHAR(100) ) AS SecretText ;
-- Use KEY_NAME to view the name of the key
SELECT KEY_NAME(@ciphertext) AS [Name of Key] ;

typeId_SchemaName #

Arguments

:: SExp 
-> SExp

typeName'

-> SExp 

Origin documentation for typeId_SchemaName

Syntax:

TYPE_ID ( [ schema_name ] type_name )

Returns the ID for a specified data type name.

Example:

USE tempdb;
GO
CREATE TYPE NewType FROM int;
GO
CREATE SCHEMA NewSchema;
GO
CREATE TYPE NewSchema.NewType FROM int;
GO
SELECT TYPE_ID('NewType') AS [1 Part Data Type ID],
       TYPE_ID('NewSchema.NewType') AS [2 Part Data Type ID];
GO

Example:

SELECT TYPE_NAME(TYPE_ID('datetime')) AS [TYPE_NAME]
    ,TYPE_ID('datetime') AS [TYPE_ID];
GO

Example:

SELECT TYPE_NAME(TYPE_ID('datetime')) AS typeName,
    TYPE_ID('datetime') AS typeID FROM table1;

typeId #

Arguments

:: SExp

typeName'

-> SExp 

Origin documentation for typeId

Syntax:

TYPE_ID ( [ schema_name ] type_name )

Returns the ID for a specified data type name.

Example:

USE tempdb;
GO
CREATE TYPE NewType FROM int;
GO
CREATE SCHEMA NewSchema;
GO
CREATE TYPE NewSchema.NewType FROM int;
GO
SELECT TYPE_ID('NewType') AS [1 Part Data Type ID],
       TYPE_ID('NewSchema.NewType') AS [2 Part Data Type ID];
GO

Example:

SELECT TYPE_NAME(TYPE_ID('datetime')) AS [TYPE_NAME]
    ,TYPE_ID('datetime') AS [TYPE_ID];
GO

Example:

SELECT TYPE_NAME(TYPE_ID('datetime')) AS typeName,
    TYPE_ID('datetime') AS typeID FROM table1;

isSrvroleMember_Login #

Arguments

:: SExp 
-> SExp

login

-> SExp 

Origin documentation for isSrvroleMember_Login

Syntax:

IS_SRVROLEMEMBER ( 'role' [ , 'login' ] )

Indicates whether a SQL Server login is a member of the specified server role.

Example:

IF IS_SRVROLEMEMBER ('sysadmin') = 1
   print 'Current user''s login is a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') = 0
   print 'Current user''s login is NOT a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') IS NULL
   print 'ERROR: The server role specified is not valid.';

Example:

SELECT IS_SRVROLEMEMBER('diskadmin', 'Contoso\Pat');

isSrvroleMember #

Arguments

:: SExp

role'

-> SExp 

Origin documentation for isSrvroleMember

Syntax:

IS_SRVROLEMEMBER ( 'role' [ , 'login' ] )

Indicates whether a SQL Server login is a member of the specified server role.

Example:

IF IS_SRVROLEMEMBER ('sysadmin') = 1
   print 'Current user''s login is a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') = 0
   print 'Current user''s login is NOT a member of the sysadmin role'
ELSE IF IS_SRVROLEMEMBER ('sysadmin') IS NULL
   print 'ERROR: The server role specified is not valid.';

Example:

SELECT IS_SRVROLEMEMBER('diskadmin', 'Contoso\Pat');

suserSName_ServerUserSid #

Arguments

:: SExp

serverUserSid

-> SExp 

Origin documentation for suserSName_ServerUserSid

Syntax:

SUSER_SNAME ( [ server_user_sid ] )

Returns the login name associated with a security identification number (SID).

Example:

SELECT SUSER_SNAME();
GO

Example:

SELECT SUSER_SNAME(0x010500000000000515000000a065cf7e784b9b5fe77c87705a2e0000);
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sname_example
(
login_sname sysname DEFAULT SUSER_SNAME(),
employee_id uniqueidentifier DEFAULT NEWID(),
login_date  datetime DEFAULT GETDATE()
);
GO
INSERT sname_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME();
GO
EXECUTE AS LOGIN = 'WanidaBenShoof';
SELECT SUSER_SNAME();
REVERT;
GO
SELECT SUSER_SNAME();
GO

Example:

SELECT SUSER_SNAME(0x01);
GO

Example:

SELECT SUSER_SNAME() AS CurrentLogin;
GO

suserSName :: SExp #

Origin documentation for suserSName

Syntax:

SUSER_SNAME ( [ server_user_sid ] )

Returns the login name associated with a security identification number (SID).

Example:

SELECT SUSER_SNAME();
GO

Example:

SELECT SUSER_SNAME(0x010500000000000515000000a065cf7e784b9b5fe77c87705a2e0000);
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sname_example
(
login_sname sysname DEFAULT SUSER_SNAME(),
employee_id uniqueidentifier DEFAULT NEWID(),
login_date  datetime DEFAULT GETDATE()
);
GO
INSERT sname_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME();
GO
EXECUTE AS LOGIN = 'WanidaBenShoof';
SELECT SUSER_SNAME();
REVERT;
GO
SELECT SUSER_SNAME();
GO

Example:

SELECT SUSER_SNAME(0x01);
GO

Example:

SELECT SUSER_SNAME() AS CurrentLogin;
GO

percentRank #

Arguments

:: Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for percentRank

Syntax:

PERCENT_RANK( )
    OVER ( [ partition_by_clause ] order_by_clause )

Calculates the relative rank of a row within a group of rows in SQL Server. Use PERCENT_RANK to evaluate the relative standing of a value within a query result set or partition. PERCENT_RANK is similar to the CUME_DIST function.

Example:

USE AdventureWorks2012;
GO
SELECT Department, LastName, Rate,
       CUME_DIST () OVER (PARTITION BY Department ORDER BY Rate) AS CumeDist,
       PERCENT_RANK() OVER (PARTITION BY Department ORDER BY Rate ) AS PctRank
FROM HumanResources.vEmployeeDepartmentHistory AS edh
    INNER JOIN HumanResources.EmployeePayHistory AS e
    ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services',N'Document Control')
ORDER BY Department, Rate DESC;

percentileCont #

Arguments

:: SExp 
-> SExp 
-> Maybe OrderDir 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for percentileCont

Syntax:

PERCENTILE_CONT ( numeric_literal )
    WITHIN GROUP ( ORDER BY order_by_expression [ ASC | DESC ] )
    OVER ( [ <partition_by_clause> ] )

Calculates a percentile based on a continuous distribution of the column value in SQL Server. The result is interpolated and might not be equal to any of the specific values in the column.

Example:

USE AdventureWorks2012;

SELECT DISTINCT Name AS DepartmentName
      ,PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ph.Rate)
                            OVER (PARTITION BY Name) AS MedianCont
      ,PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY ph.Rate)
                            OVER (PARTITION BY Name) AS MedianDisc
FROM HumanResources.Department AS d
INNER JOIN HumanResources.EmployeeDepartmentHistory AS dh
    ON dh.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.EmployeePayHistory AS ph
    ON ph.BusinessEntityID = dh.BusinessEntityID
WHERE dh.EndDate IS NULL;

Example:

-- Uses AdventureWorks

SELECT DISTINCT DepartmentName
,PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY BaseRate)
    OVER (PARTITION BY DepartmentName) AS MedianCont
,PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY BaseRate)
    OVER (PARTITION BY DepartmentName) AS MedianDisc
FROM dbo.DimEmployee;

suserName_ServerUserId #

Arguments

:: SExp

serverUserId

-> SExp 

Origin documentation for suserName_ServerUserId

Syntax:

SUSER_NAME ( [ server_user_id ] )

Returns the login identification name of the user.

Example:

SELECT SUSER_NAME(1);

suserName :: SExp #

Origin documentation for suserName

Syntax:

SUSER_NAME ( [ server_user_id ] )

Returns the login identification name of the user.

Example:

SELECT SUSER_NAME(1);

format_Culture #

Arguments

:: SExp 
-> SExp 
-> SExp

culture

-> SExp 

Origin documentation for format_Culture

Syntax:

FORMAT( value, format [, culture ] )

Returns a value formatted with the specified format and optional culture. Use the FORMAT function for locale-aware formatting of date/time and number values as strings. For general data type conversions, use CAST or CONVERT.

Example:

DECLARE @d DATE = '11/22/2020';
SELECT FORMAT( @d, 'd', 'en-US' ) 'US English'
      ,FORMAT( @d, 'd', 'en-gb' ) 'British English'
      ,FORMAT( @d, 'd', 'de-de' ) 'German'
      ,FORMAT( @d, 'd', 'zh-cn' ) 'Chinese Simplified (PRC)';

SELECT FORMAT( @d, 'D', 'en-US' ) 'US English'
      ,FORMAT( @d, 'D', 'en-gb' ) 'British English'
      ,FORMAT( @d, 'D', 'de-de' ) 'German'
      ,FORMAT( @d, 'D', 'zh-cn' ) 'Chinese Simplified (PRC)';

Example:

DECLARE @d DATE = GETDATE();
SELECT FORMAT( @d, 'dd/MM/yyyy', 'en-US' ) AS 'Date'
       ,FORMAT(123456789,'###-##-####') AS 'Custom Number';

Example:

SELECT TOP(5) CurrencyRateID, EndOfDayRate
            ,FORMAT(EndOfDayRate, 'N', 'en-us') AS 'Numeric Format'
            ,FORMAT(EndOfDayRate, 'G', 'en-us') AS 'General Format'
            ,FORMAT(EndOfDayRate, 'C', 'en-us') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;

Example:

SELECT TOP(5) CurrencyRateID, EndOfDayRate
      ,FORMAT(EndOfDayRate, 'N', 'de-de') AS 'Numeric Format'
      ,FORMAT(EndOfDayRate, 'G', 'de-de') AS 'General Format'
      ,FORMAT(EndOfDayRate, 'C', 'de-de') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;

Example:

SELECT FORMAT(cast('07:35' as time), N'hh.mm');   --> returns NULL
SELECT FORMAT(cast('07:35' as time), N'hh:mm');   --> returns NULL

Example:

SELECT FORMAT(cast('07:35' as time), N'hh\.mm');  --> returns 07.35
SELECT FORMAT(cast('07:35' as time), N'hh\:mm');  --> returns 07:35

Example:

SELECT FORMAT(SYSDATETIME(), N'hh:mm tt'); -- returns 03:46 PM
SELECT FORMAT(SYSDATETIME(), N'hh:mm t'); -- returns 03:46 P

Example:

select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm tt') -- returns 01:00 AM
select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm t')  -- returns 01:00 A

Example:

select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm tt') -- returns 02:00 PM
select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm t') -- returns 02:00 P

Example:

select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'HH:mm') -- returns 14:00

format #

Arguments

:: SExp 
-> SExp

format'

-> SExp 

Origin documentation for format

Syntax:

FORMAT( value, format [, culture ] )

Returns a value formatted with the specified format and optional culture. Use the FORMAT function for locale-aware formatting of date/time and number values as strings. For general data type conversions, use CAST or CONVERT.

Example:

DECLARE @d DATE = '11/22/2020';
SELECT FORMAT( @d, 'd', 'en-US' ) 'US English'
      ,FORMAT( @d, 'd', 'en-gb' ) 'British English'
      ,FORMAT( @d, 'd', 'de-de' ) 'German'
      ,FORMAT( @d, 'd', 'zh-cn' ) 'Chinese Simplified (PRC)';

SELECT FORMAT( @d, 'D', 'en-US' ) 'US English'
      ,FORMAT( @d, 'D', 'en-gb' ) 'British English'
      ,FORMAT( @d, 'D', 'de-de' ) 'German'
      ,FORMAT( @d, 'D', 'zh-cn' ) 'Chinese Simplified (PRC)';

Example:

DECLARE @d DATE = GETDATE();
SELECT FORMAT( @d, 'dd/MM/yyyy', 'en-US' ) AS 'Date'
       ,FORMAT(123456789,'###-##-####') AS 'Custom Number';

Example:

SELECT TOP(5) CurrencyRateID, EndOfDayRate
            ,FORMAT(EndOfDayRate, 'N', 'en-us') AS 'Numeric Format'
            ,FORMAT(EndOfDayRate, 'G', 'en-us') AS 'General Format'
            ,FORMAT(EndOfDayRate, 'C', 'en-us') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;

Example:

SELECT TOP(5) CurrencyRateID, EndOfDayRate
      ,FORMAT(EndOfDayRate, 'N', 'de-de') AS 'Numeric Format'
      ,FORMAT(EndOfDayRate, 'G', 'de-de') AS 'General Format'
      ,FORMAT(EndOfDayRate, 'C', 'de-de') AS 'Currency Format'
FROM Sales.CurrencyRate
ORDER BY CurrencyRateID;

Example:

SELECT FORMAT(cast('07:35' as time), N'hh.mm');   --> returns NULL
SELECT FORMAT(cast('07:35' as time), N'hh:mm');   --> returns NULL

Example:

SELECT FORMAT(cast('07:35' as time), N'hh\.mm');  --> returns 07.35
SELECT FORMAT(cast('07:35' as time), N'hh\:mm');  --> returns 07:35

Example:

SELECT FORMAT(SYSDATETIME(), N'hh:mm tt'); -- returns 03:46 PM
SELECT FORMAT(SYSDATETIME(), N'hh:mm t'); -- returns 03:46 P

Example:

select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm tt') -- returns 01:00 AM
select FORMAT(CAST('2018-01-01 01:00' AS datetime2), N'hh:mm t')  -- returns 01:00 A

Example:

select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm tt') -- returns 02:00 PM
select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'hh:mm t') -- returns 02:00 P

Example:

select FORMAT(CAST('2018-01-01 14:00' AS datetime2), N'HH:mm') -- returns 14:00

decryptByKey_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for decryptByKey_AddAuthenticator_Authenticator

Syntax:

DecryptByKey ( { 'ciphertext' | @ciphertext }
    [ , add_authenticator, { authenticator | @authenticator } ] )

This function uses a symmetric key to decrypt data.

Note

This syntax is not supported by serverless SQL pool in Azure Synapse Analytics.

For dedicated SQL pools in Azure Synapse Analytics, result set caching should not be used in conjunction with DECRYPTBYKEY. If this cryptographic function must be used, ensure you have result set caching disabled (either at session-level or database-level ) at the time of execution.

Example:

-- First, open the symmetric key with which to decrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
GO

-- Now list the original ID, the encrypted ID, and the
-- decrypted ciphertext. If the decryption worked, the original
-- and the decrypted ID will match.
SELECT NationalIDNumber, EncryptedNationalID
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalID))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

Example:

-- First, open the symmetric key with which to decrypt the data
OPEN SYMMETRIC KEY CreditCards_Key11
   DECRYPTION BY CERTIFICATE Sales09;
GO

-- Now list the original card number, the encrypted card number,
-- and the decrypted ciphertext. If the decryption worked,
-- the original number will match the decrypted number.
SELECT CardNumber, CardNumber_Encrypted
    AS 'Encrypted card number', CONVERT(nvarchar,
    DecryptByKey(CardNumber_Encrypted, 1 ,
    HashBytes('SHA1', CONVERT(varbinary, CreditCardID))))
    AS 'Decrypted card number' FROM Sales.CreditCard;
GO

Example:

-- Create the database
CREATE DATABASE TestingDecryptByKey
GO

USE [TestingDecryptByKey]

-- Create the table and view
CREATE TABLE TestingDecryptByKey.dbo.Test(val VARBINARY(8000) NOT NULL);
GO
CREATE VIEW dbo.TestView AS SELECT CAST(DecryptByKey(val) AS VARCHAR(30)) AS DecryptedVal FROM TestingDecryptByKey.dbo.Test;
GO

-- Create the key, and certificate
USE TestingDecryptByKey;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'ItIsreallyLong1AndSecured!Passsword#';
CREATE CERTIFICATE TestEncryptionCertificate WITH SUBJECT = 'TestEncryption';
CREATE SYMMETRIC KEY TestEncryptSymmmetricKey WITH ALGORITHM = AES_256, IDENTITY_VALUE = 'It is place for test',
KEY_SOURCE = 'It is source for test' ENCRYPTION BY CERTIFICATE TestEncryptionCertificate;

-- Insert rows into the table
DECLARE @var VARBINARY(8000), @Val VARCHAR(30);
SELECT @Val = '000-123-4567';
OPEN SYMMETRIC KEY TestEncryptSymmmetricKey DECRYPTION BY CERTIFICATE TestEncryptionCertificate;
SELECT @var = EncryptByKey(Key_GUID('TestEncryptSymmmetricKey'), @Val);
SELECT CAST(DecryptByKey(@var) AS VARCHAR(30)), @Val;
INSERT INTO dbo.Test VALUES(@var);
GO

-- Switch to master
USE [Master];
GO

-- Results show the date inserted
SELECT DecryptedVal FROM TestingDecryptByKey.dbo.TestView;

-- Results are NULL because we are not in the context of the TestingDecryptByKey Database
SELECT CAST(DecryptByKey(val) AS VARCHAR(30)) AS DecryptedVal FROM TestingDecryptByKey.dbo.Test;
GO

-- Clean up resources
USE TestingDecryptByKey;

DROP SYMMETRIC KEY TestEncryptSymmmetricKey REMOVE PROVIDER KEY;
DROP CERTIFICATE TestEncryptionCertificate;

Use [Master]
DROP DATABASE TestingDecryptByKey;
GO

decryptByKey #

Arguments

:: SExp

ciphertext

-> SExp 

Origin documentation for decryptByKey

Syntax:

DecryptByKey ( { 'ciphertext' | @ciphertext }
    [ , add_authenticator, { authenticator | @authenticator } ] )

This function uses a symmetric key to decrypt data.

Note

This syntax is not supported by serverless SQL pool in Azure Synapse Analytics.

For dedicated SQL pools in Azure Synapse Analytics, result set caching should not be used in conjunction with DECRYPTBYKEY. If this cryptographic function must be used, ensure you have result set caching disabled (either at session-level or database-level ) at the time of execution.

Example:

-- First, open the symmetric key with which to decrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
GO

-- Now list the original ID, the encrypted ID, and the
-- decrypted ciphertext. If the decryption worked, the original
-- and the decrypted ID will match.
SELECT NationalIDNumber, EncryptedNationalID
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalID))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

Example:

-- First, open the symmetric key with which to decrypt the data
OPEN SYMMETRIC KEY CreditCards_Key11
   DECRYPTION BY CERTIFICATE Sales09;
GO

-- Now list the original card number, the encrypted card number,
-- and the decrypted ciphertext. If the decryption worked,
-- the original number will match the decrypted number.
SELECT CardNumber, CardNumber_Encrypted
    AS 'Encrypted card number', CONVERT(nvarchar,
    DecryptByKey(CardNumber_Encrypted, 1 ,
    HashBytes('SHA1', CONVERT(varbinary, CreditCardID))))
    AS 'Decrypted card number' FROM Sales.CreditCard;
GO

Example:

-- Create the database
CREATE DATABASE TestingDecryptByKey
GO

USE [TestingDecryptByKey]

-- Create the table and view
CREATE TABLE TestingDecryptByKey.dbo.Test(val VARBINARY(8000) NOT NULL);
GO
CREATE VIEW dbo.TestView AS SELECT CAST(DecryptByKey(val) AS VARCHAR(30)) AS DecryptedVal FROM TestingDecryptByKey.dbo.Test;
GO

-- Create the key, and certificate
USE TestingDecryptByKey;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'ItIsreallyLong1AndSecured!Passsword#';
CREATE CERTIFICATE TestEncryptionCertificate WITH SUBJECT = 'TestEncryption';
CREATE SYMMETRIC KEY TestEncryptSymmmetricKey WITH ALGORITHM = AES_256, IDENTITY_VALUE = 'It is place for test',
KEY_SOURCE = 'It is source for test' ENCRYPTION BY CERTIFICATE TestEncryptionCertificate;

-- Insert rows into the table
DECLARE @var VARBINARY(8000), @Val VARCHAR(30);
SELECT @Val = '000-123-4567';
OPEN SYMMETRIC KEY TestEncryptSymmmetricKey DECRYPTION BY CERTIFICATE TestEncryptionCertificate;
SELECT @var = EncryptByKey(Key_GUID('TestEncryptSymmmetricKey'), @Val);
SELECT CAST(DecryptByKey(@var) AS VARCHAR(30)), @Val;
INSERT INTO dbo.Test VALUES(@var);
GO

-- Switch to master
USE [Master];
GO

-- Results show the date inserted
SELECT DecryptedVal FROM TestingDecryptByKey.dbo.TestView;

-- Results are NULL because we are not in the context of the TestingDecryptByKey Database
SELECT CAST(DecryptByKey(val) AS VARCHAR(30)) AS DecryptedVal FROM TestingDecryptByKey.dbo.Test;
GO

-- Clean up resources
USE TestingDecryptByKey;

DROP SYMMETRIC KEY TestEncryptSymmmetricKey REMOVE PROVIDER KEY;
DROP CERTIFICATE TestEncryptionCertificate;

Use [Master]
DROP DATABASE TestingDecryptByKey;
GO

jsonArray #

Arguments

:: [SExp] 
-> Maybe JsonNullStrategy

maybeJsonnullstrategy

-> SExp 

Origin documentation for jsonArray

Syntax:

JSON_ARRAY ( [ <json_array_value> [,...n] ] [ <json_null_clause> ]  )

<json_array_value> ::= value_expression

<json_null_clause> ::=
	  NULL ON NULL
	| ABSENT ON NULL

Constructs JSON array text from zero or more expressions.

Example:

SELECT JSON_ARRAY();

Example:

SELECT JSON_ARRAY('a', 1, 'b', 2)

Example:

SELECT JSON_ARRAY('a', 1, 'b', NULL)

Example:

SELECT JSON_ARRAY('a', 1, NULL, 2 NULL ON NULL)

Example:

SELECT JSON_ARRAY('a', JSON_OBJECT('name':'value', 'type':1))

Example:

SELECT JSON_ARRAY('a', JSON_OBJECT('name':'value', 'type':1), JSON_ARRAY(1, null, 2 NULL ON NULL))

Example:

DECLARE @id_value nvarchar(64) = NEWID();
SELECT JSON_ARRAY(1, @id_value, (SELECT @@SPID));

Example:

SELECT s.session_id, JSON_ARRAY(s.host_name, s.program_name, s.client_interface_name)
FROM sys.dm_exec_sessions AS s
WHERE s.is_user_process = 1;

signByCert_Password #

Arguments

:: SExp 
-> SExp 
-> SExp

password

-> SExp 

Origin documentation for signByCert_Password

Syntax:

SignByCert ( certificate_ID , @cleartext [ , 'password' ] )

Signs text with a certificate and returns the signature.

Example:

DECLARE @SensitiveData NVARCHAR(max);
SET @SensitiveData = N'Saddle Price Points are
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29';
INSERT INTO [SignedData04]
    VALUES( N'data signed by certificate ''ABerglundCert07''',
    @SensitiveData, SignByCert( Cert_Id( 'ABerglundCert07' ),
    @SensitiveData, N'pGFD4bb925DGvbd2439587y' ));
GO

signByCert #

Arguments

:: SExp 
-> SExp

cleartext

-> SExp 

Origin documentation for signByCert

Syntax:

SignByCert ( certificate_ID , @cleartext [ , 'password' ] )

Signs text with a certificate and returns the signature.

Example:

DECLARE @SensitiveData NVARCHAR(max);
SET @SensitiveData = N'Saddle Price Points are
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29';
INSERT INTO [SignedData04]
    VALUES( N'data signed by certificate ''ABerglundCert07''',
    @SensitiveData, SignByCert( Cert_Id( 'ABerglundCert07' ),
    @SensitiveData, N'pGFD4bb925DGvbd2439587y' ));
GO

suserSid_Login_Param2 #

Arguments

:: SExp 
-> SExp

param2

-> SExp 

Origin documentation for suserSid_Login_Param2

Syntax:

SUSER_SID ( [ 'login' ] [ , Param2 ] )

Returns the security identification number (SID) for the specified login name.

Example:

SELECT SUSER_SID();

Example:

SELECT SUSER_SID('sa');
GO

Example:

SELECT SUSER_SID('London\Workstation1');
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sid_example
(
login_sid   VARBINARY(85) DEFAULT SUSER_SID(),
login_name  VARCHAR(30) DEFAULT SYSTEM_USER,
login_dept  VARCHAR(10) DEFAULT 'SALES',
login_date  DATETIME DEFAULT GETDATE()
);
GO
INSERT sid_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME(SUSER_SID('TestComputer\User', 0));

suserSid_Login #

Arguments

:: SExp

login

-> SExp 

Origin documentation for suserSid_Login

Syntax:

SUSER_SID ( [ 'login' ] [ , Param2 ] )

Returns the security identification number (SID) for the specified login name.

Example:

SELECT SUSER_SID();

Example:

SELECT SUSER_SID('sa');
GO

Example:

SELECT SUSER_SID('London\Workstation1');
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sid_example
(
login_sid   VARBINARY(85) DEFAULT SUSER_SID(),
login_name  VARCHAR(30) DEFAULT SYSTEM_USER,
login_dept  VARCHAR(10) DEFAULT 'SALES',
login_date  DATETIME DEFAULT GETDATE()
);
GO
INSERT sid_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME(SUSER_SID('TestComputer\User', 0));

suserSid_Param2 #

Arguments

:: SExp

param2

-> SExp 

Origin documentation for suserSid_Param2

Syntax:

SUSER_SID ( [ 'login' ] [ , Param2 ] )

Returns the security identification number (SID) for the specified login name.

Example:

SELECT SUSER_SID();

Example:

SELECT SUSER_SID('sa');
GO

Example:

SELECT SUSER_SID('London\Workstation1');
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sid_example
(
login_sid   VARBINARY(85) DEFAULT SUSER_SID(),
login_name  VARCHAR(30) DEFAULT SYSTEM_USER,
login_dept  VARCHAR(10) DEFAULT 'SALES',
login_date  DATETIME DEFAULT GETDATE()
);
GO
INSERT sid_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME(SUSER_SID('TestComputer\User', 0));

suserSid :: SExp #

Origin documentation for suserSid

Syntax:

SUSER_SID ( [ 'login' ] [ , Param2 ] )

Returns the security identification number (SID) for the specified login name.

Example:

SELECT SUSER_SID();

Example:

SELECT SUSER_SID('sa');
GO

Example:

SELECT SUSER_SID('London\Workstation1');
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE sid_example
(
login_sid   VARBINARY(85) DEFAULT SUSER_SID(),
login_name  VARCHAR(30) DEFAULT SYSTEM_USER,
login_dept  VARCHAR(10) DEFAULT 'SALES',
login_date  DATETIME DEFAULT GETDATE()
);
GO
INSERT sid_example DEFAULT VALUES;
GO

Example:

SELECT SUSER_SNAME(SUSER_SID('TestComputer\User', 0));

permissions_Objectid_Column #

Arguments

:: SExp 
-> SExp

column

-> SExp 

Origin documentation for permissions_Objectid_Column

Syntax:

PERMISSIONS ( [ objectid [ , 'column' ] ] )

Returns a value containing a bitmap that indicates the statement, object, or column permissions of the current user.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use fn_my_permissions and Has_Perms_By_Name instead. Continued use of the PERMISSIONS function may result in slower performance.

Example:

IF PERMISSIONS()&2=2
   CREATE TABLE test_table (col1 INT)
ELSE
   PRINT 'ERROR: The current user cannot create a table.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&8=8
   PRINT 'The current user can insert data into Person.Address.'
ELSE
   PRINT 'ERROR: The current user cannot insert data into Person.Address.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&0x80000=0x80000
   PRINT 'INSERT on Person.Address is grantable.'
ELSE
   PRINT 'You may not GRANT INSERT permissions on Person.Address.';

permissions_Objectid #

Arguments

:: SExp

objectid

-> SExp 

Origin documentation for permissions_Objectid

Syntax:

PERMISSIONS ( [ objectid [ , 'column' ] ] )

Returns a value containing a bitmap that indicates the statement, object, or column permissions of the current user.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use fn_my_permissions and Has_Perms_By_Name instead. Continued use of the PERMISSIONS function may result in slower performance.

Example:

IF PERMISSIONS()&2=2
   CREATE TABLE test_table (col1 INT)
ELSE
   PRINT 'ERROR: The current user cannot create a table.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&8=8
   PRINT 'The current user can insert data into Person.Address.'
ELSE
   PRINT 'ERROR: The current user cannot insert data into Person.Address.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&0x80000=0x80000
   PRINT 'INSERT on Person.Address is grantable.'
ELSE
   PRINT 'You may not GRANT INSERT permissions on Person.Address.';

permissions :: SExp #

Origin documentation for permissions

Syntax:

PERMISSIONS ( [ objectid [ , 'column' ] ] )

Returns a value containing a bitmap that indicates the statement, object, or column permissions of the current user.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use fn_my_permissions and Has_Perms_By_Name instead. Continued use of the PERMISSIONS function may result in slower performance.

Example:

IF PERMISSIONS()&2=2
   CREATE TABLE test_table (col1 INT)
ELSE
   PRINT 'ERROR: The current user cannot create a table.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&8=8
   PRINT 'The current user can insert data into Person.Address.'
ELSE
   PRINT 'ERROR: The current user cannot insert data into Person.Address.';

Example:

IF PERMISSIONS(OBJECT_ID('AdventureWorks2012.Person.Address','U'))&0x80000=0x80000
   PRINT 'INSERT on Person.Address is grantable.'
ELSE
   PRINT 'You may not GRANT INSERT permissions on Person.Address.';

decryptByPassPhrase_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for decryptByPassPhrase_AddAuthenticator_Authenticator

Syntax:

DecryptByPassPhrase ( { 'passphrase' | @passphrase }
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
    , { authenticator | @authenticator } ] )

This function decrypts data originally encrypted with a passphrase.

Example:

USE AdventureWorks2012;
-- Get the passphrase from the user.
DECLARE @PassphraseEnteredByUser NVARCHAR(128);
SET @PassphraseEnteredByUser
= 'A little learning is a dangerous thing!';

-- Decrypt the encrypted record.
SELECT CardNumber, CardNumber_EncryptedbyPassphrase
    AS 'Encrypted card number', CONVERT(varchar,
    DecryptByPassphrase(@PassphraseEnteredByUser, CardNumber_EncryptedbyPassphrase, 1
    , CONVERT(varbinary, CreditCardID)))
    AS 'Decrypted card number' FROM Sales.CreditCard
    WHERE CreditCardID = '3681';
GO

decryptByPassPhrase #

Arguments

:: SExp 
-> SExp

ciphertext

-> SExp 

Origin documentation for decryptByPassPhrase

Syntax:

DecryptByPassPhrase ( { 'passphrase' | @passphrase }
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
    , { authenticator | @authenticator } ] )

This function decrypts data originally encrypted with a passphrase.

Example:

USE AdventureWorks2012;
-- Get the passphrase from the user.
DECLARE @PassphraseEnteredByUser NVARCHAR(128);
SET @PassphraseEnteredByUser
= 'A little learning is a dangerous thing!';

-- Decrypt the encrypted record.
SELECT CardNumber, CardNumber_EncryptedbyPassphrase
    AS 'Encrypted card number', CONVERT(varchar,
    DecryptByPassphrase(@PassphraseEnteredByUser, CardNumber_EncryptedbyPassphrase, 1
    , CONVERT(varbinary, CreditCardID)))
    AS 'Decrypted card number' FROM Sales.CreditCard
    WHERE CreditCardID = '3681';
GO

symKeyProperty_Sid #

Arguments

:: SExp

sid

-> SExp 

Origin documentation for symKeyProperty_Sid

Syntax:

SYMKEYPROPERTY ( Key_ID , 'algorithm_desc' | 'string_sid' | 'sid' )

Returns the algorithm of a symmetric key created from an EKM module.

Example:

SELECT SYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm ;
GO

symKeyProperty_StringSid #

Arguments

:: SExp

stringSid

-> SExp 

Origin documentation for symKeyProperty_StringSid

Syntax:

SYMKEYPROPERTY ( Key_ID , 'algorithm_desc' | 'string_sid' | 'sid' )

Returns the algorithm of a symmetric key created from an EKM module.

Example:

SELECT SYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm ;
GO

symKeyProperty_KeyId_AlgorithmDesc #

Arguments

:: SExp 
-> SExp

algorithmDesc

-> SExp 

Origin documentation for symKeyProperty_KeyId_AlgorithmDesc

Syntax:

SYMKEYPROPERTY ( Key_ID , 'algorithm_desc' | 'string_sid' | 'sid' )

Returns the algorithm of a symmetric key created from an EKM module.

Example:

SELECT SYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm ;
GO

objectId_SchemaName_ObjectType #

Arguments

:: SExp 
-> SExp 
-> SExp

objectType

-> SExp 

Origin documentation for objectId_SchemaName_ObjectType

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_SchemaName #

Arguments

:: SExp 
-> SExp

objectName'

-> SExp 

Origin documentation for objectId_SchemaName

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_DatabaseName_SchemaName_ObjectType #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

objectType

-> SExp 

Origin documentation for objectId_DatabaseName_SchemaName_ObjectType

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_DatabaseName_SchemaName #

Arguments

:: SExp 
-> SExp 
-> SExp

objectName'

-> SExp 

Origin documentation for objectId_DatabaseName_SchemaName

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_DatabaseName_ObjectType #

Arguments

:: SExp 
-> SExp 
-> SExp

objectType

-> SExp 

Origin documentation for objectId_DatabaseName_ObjectType

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_DatabaseName #

Arguments

:: SExp 
-> SExp

objectName'

-> SExp 

Origin documentation for objectId_DatabaseName

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId_ObjectType #

Arguments

:: SExp 
-> SExp

objectType

-> SExp 

Origin documentation for objectId_ObjectType

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

objectId #

Arguments

:: SExp

objectName'

-> SExp 

Origin documentation for objectId

Syntax:

OBJECT_ID ( '[ database_name . [ schema_name ] . | schema_name . ]
  object_name' [ ,'object_type' ] )

Returns the database object identification number of a schema-scoped object.

Important

Objects that are not schema-scoped, such as DDL triggers, cannot be queried by using OBJECT_ID. For objects that are not found in the sys.objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys.triggers WHERE name = DatabaseTriggerLog`' .

Example:

USE master;
GO
SELECT OBJECT_ID(N'AdventureWorks2012.Production.WorkOrder') AS 'Object ID';
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'dbo.AWBuildVersion', N'U') IS NOT NULL
DROP TABLE dbo.AWBuildVersion;
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT OBJECT_ID('AdventureWorksPDW2012.dbo.FactFinance') AS 'Object ID';

tryCast_Length #

Arguments

:: SExp 
-> SExp 
-> SExp

length'

-> SExp 

Origin documentation for tryCast_Length

Syntax:

TRY_CAST ( expression AS data_type [ ( length ) ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CAST('test' AS float) IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
GO

Example:

SELECT TRY_CAST(4 AS xml) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
GO

tryCast #

Arguments

:: SExp 
-> SExp

dataType

-> SExp 

Origin documentation for tryCast

Syntax:

TRY_CAST ( expression AS data_type [ ( length ) ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CAST('test' AS float) IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
GO

Example:

SELECT TRY_CAST(4 AS xml) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CAST('12/31/2010' AS datetime2) AS Result;
GO

lastValue_ScalarExpression #

Arguments

:: SExp 
-> Maybe NullStrategy 
-> Maybe PartitionBy 
-> OverOrderBy 
-> Maybe RowRange

maybeRowrange

-> SExp 

Origin documentation for lastValue_ScalarExpression

Syntax:

LAST_VALUE ( [ scalar_expression ] )  [ IGNORE NULLS | RESPECT NULLS ]
    OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )

Returns the last value in an ordered set of values.

Example:

USE AdventureWorks2012;
GO
SELECT Department
    , LastName
    , Rate
    , HireDate
    , LAST_VALUE(HireDate) OVER (
        PARTITION BY Department ORDER BY Rate
        ) AS LastValue
FROM HumanResources.vEmployeeDepartmentHistory AS edh
INNER JOIN HumanResources.EmployeePayHistory AS eph
    ON eph.BusinessEntityID = edh.BusinessEntityID
INNER JOIN HumanResources.Employee AS e
    ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services', N'Document Control');

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID
    , DATEPART(QUARTER, QuotaDate) AS Quarter
    , YEAR(QuotaDate) AS SalesYear
    , SalesQuota AS QuotaThisQuarter
    , SalesQuota - FIRST_VALUE(SalesQuota)
          OVER (PARTITION BY BusinessEntityID, YEAR(QuotaDate)
              ORDER BY DATEPART(QUARTER, QuotaDate)) AS DifferenceFromFirstQuarter
    , SalesQuota - LAST_VALUE(SalesQuota)
          OVER (PARTITION BY BusinessEntityID, YEAR(QuotaDate)
              ORDER BY DATEPART(QUARTER, QuotaDate)
              RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS DifferenceFromLastQuarter
FROM Sales.SalesPersonQuotaHistory
WHERE YEAR(QuotaDate) > 2005 AND BusinessEntityID BETWEEN 274 AND 275
ORDER BY BusinessEntityID, SalesYear, Quarter;

lastValue #

Arguments

:: Maybe NullStrategy 
-> Maybe PartitionBy 
-> OverOrderBy 
-> Maybe RowRange

maybeRowrange

-> SExp 

Origin documentation for lastValue

Syntax:

LAST_VALUE ( [ scalar_expression ] )  [ IGNORE NULLS | RESPECT NULLS ]
    OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )

Returns the last value in an ordered set of values.

Example:

USE AdventureWorks2012;
GO
SELECT Department
    , LastName
    , Rate
    , HireDate
    , LAST_VALUE(HireDate) OVER (
        PARTITION BY Department ORDER BY Rate
        ) AS LastValue
FROM HumanResources.vEmployeeDepartmentHistory AS edh
INNER JOIN HumanResources.EmployeePayHistory AS eph
    ON eph.BusinessEntityID = edh.BusinessEntityID
INNER JOIN HumanResources.Employee AS e
    ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services', N'Document Control');

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID
    , DATEPART(QUARTER, QuotaDate) AS Quarter
    , YEAR(QuotaDate) AS SalesYear
    , SalesQuota AS QuotaThisQuarter
    , SalesQuota - FIRST_VALUE(SalesQuota)
          OVER (PARTITION BY BusinessEntityID, YEAR(QuotaDate)
              ORDER BY DATEPART(QUARTER, QuotaDate)) AS DifferenceFromFirstQuarter
    , SalesQuota - LAST_VALUE(SalesQuota)
          OVER (PARTITION BY BusinessEntityID, YEAR(QuotaDate)
              ORDER BY DATEPART(QUARTER, QuotaDate)
              RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS DifferenceFromLastQuarter
FROM Sales.SalesPersonQuotaHistory
WHERE YEAR(QuotaDate) > 2005 AND BusinessEntityID BETWEEN 274 AND 275
ORDER BY BusinessEntityID, SalesYear, Quarter;

dbName_DatabaseId #

Arguments

:: SExp

databaseId

-> SExp 

Origin documentation for dbName_DatabaseId

Syntax:

DB_NAME ( [ database_id ] )

This function returns the name of a specified database.

Example:

SELECT DB_NAME() AS [Current Database];
GO

Example:

USE master;
GO
SELECT DB_NAME(3) AS [Database Name];
GO

Example:

SELECT DB_NAME() AS [Current Database];

Example:

SELECT DB_NAME(database_id) AS [Database], database_id
FROM sys.databases;

dbName :: SExp #

Origin documentation for dbName

Syntax:

DB_NAME ( [ database_id ] )

This function returns the name of a specified database.

Example:

SELECT DB_NAME() AS [Current Database];
GO

Example:

USE master;
GO
SELECT DB_NAME(3) AS [Database Name];
GO

Example:

SELECT DB_NAME() AS [Current Database];

Example:

SELECT DB_NAME(database_id) AS [Database], database_id
FROM sys.databases;

schemaId_SchemaName #

Arguments

:: SExp

schemaName'

-> SExp 

Origin documentation for schemaId_SchemaName

Syntax:

SCHEMA_ID ( [ schema_name ] )

Returns the schema ID associated with a schema name.

Example:

SELECT SCHEMA_ID();

Example:

SELECT SCHEMA_ID('dbo');

schemaId :: SExp #

Origin documentation for schemaId

Syntax:

SCHEMA_ID ( [ schema_name ] )

Returns the schema ID associated with a schema name.

Example:

SELECT SCHEMA_ID();

Example:

SELECT SCHEMA_ID('dbo');

lag_Offset_Default #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lag_Offset_Default

Syntax:

LAG (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
       LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS PreviousQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LAG(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear, CalendarQuarter, SalesAmountQuota AS SalesQuota,
       LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS PrevQuota,
       SalesAmountQuota - LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001, 2002)
ORDER BY CalendarYear, CalendarQuarter;

lag_Offset #

Arguments

:: SExp 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lag_Offset

Syntax:

LAG (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
       LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS PreviousQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LAG(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear, CalendarQuarter, SalesAmountQuota AS SalesQuota,
       LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS PrevQuota,
       SalesAmountQuota - LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001, 2002)
ORDER BY CalendarYear, CalendarQuarter;

lag #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lag

Syntax:

LAG (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a previous row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LAG provides access to a row at a given physical offset that comes before the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a previous row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
       LAG(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS PreviousQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LAG(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear, CalendarQuarter, SalesAmountQuota AS SalesQuota,
       LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS PrevQuota,
       SalesAmountQuota - LAG(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001, 2002)
ORDER BY CalendarYear, CalendarQuarter;

firstValue_ScalarExpression #

Arguments

:: SExp 
-> Maybe NullStrategy 
-> Maybe PartitionBy 
-> OverOrderBy 
-> Maybe RowRange

maybeRowrange

-> SExp 

Origin documentation for firstValue_ScalarExpression

Syntax:

FIRST_VALUE ( [scalar_expression ] )  [ IGNORE NULLS | RESPECT NULLS ]
    OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )

Returns the first value in an ordered set of values.

Example:

USE AdventureWorks2012;
GO
SELECT Name, ListPrice,
       FIRST_VALUE(Name) OVER (ORDER BY ListPrice ASC) AS LeastExpensive
FROM Production.Product
WHERE ProductSubcategoryID = 37;

Example:

USE AdventureWorks2012;
GO
SELECT JobTitle, LastName, VacationHours,
       FIRST_VALUE(LastName) OVER (PARTITION BY JobTitle
                                   ORDER BY VacationHours ASC
                                   ROWS UNBOUNDED PRECEDING
                                  ) AS FewestVacationHours
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
    ON e.BusinessEntityID = p.BusinessEntityID
ORDER BY JobTitle;

firstValue #

Arguments

:: Maybe NullStrategy 
-> Maybe PartitionBy 
-> OverOrderBy 
-> Maybe RowRange

maybeRowrange

-> SExp 

Origin documentation for firstValue

Syntax:

FIRST_VALUE ( [scalar_expression ] )  [ IGNORE NULLS | RESPECT NULLS ]
    OVER ( [ partition_by_clause ] order_by_clause [ rows_range_clause ] )

Returns the first value in an ordered set of values.

Example:

USE AdventureWorks2012;
GO
SELECT Name, ListPrice,
       FIRST_VALUE(Name) OVER (ORDER BY ListPrice ASC) AS LeastExpensive
FROM Production.Product
WHERE ProductSubcategoryID = 37;

Example:

USE AdventureWorks2012;
GO
SELECT JobTitle, LastName, VacationHours,
       FIRST_VALUE(LastName) OVER (PARTITION BY JobTitle
                                   ORDER BY VacationHours ASC
                                   ROWS UNBOUNDED PRECEDING
                                  ) AS FewestVacationHours
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
    ON e.BusinessEntityID = p.BusinessEntityID
ORDER BY JobTitle;

percentileDisc #

Arguments

:: SExp 
-> SExp 
-> Maybe OrderDir 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for percentileDisc

Syntax:

PERCENTILE_DISC ( numeric_literal ) WITHIN GROUP ( ORDER BY order_by_expression [ ASC | DESC ] )
    OVER ( [ <partition_by_clause> ] )

Computes a specific percentile for sorted values in an entire rowset or within a rowset's distinct partitions in SQL Server. For a given percentile value P , PERCENTILE_DISC sorts the expression values in the ORDER BY clause. It then returns the value with the smallest CUME_DIST value given (with respect to the same sort specification) that is greater than or equal to P . For example, PERCENTILE_DISC (0.5) will compute the 50th percentile (that is, the median) of an expression. PERCENTILE_DISC calculates the percentile based on a discrete distribution of the column values. The result is equal to a specific column value.

Example:

USE AdventureWorks2012;

SELECT DISTINCT Name AS DepartmentName
      ,PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ph.Rate)
                            OVER (PARTITION BY Name) AS MedianCont
      ,PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY ph.Rate)
                            OVER (PARTITION BY Name) AS MedianDisc
FROM HumanResources.Department AS d
INNER JOIN HumanResources.EmployeeDepartmentHistory AS dh
    ON dh.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.EmployeePayHistory AS ph
    ON ph.BusinessEntityID = dh.BusinessEntityID
WHERE dh.EndDate IS NULL;

Example:

-- Uses AdventureWorks

SELECT DISTINCT DepartmentName
       ,PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY BaseRate)
        OVER (PARTITION BY DepartmentName) AS MedianCont
       ,PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY BaseRate)
        OVER (PARTITION BY DepartmentName) AS MedianDisc
FROM dbo.DimEmployee;

decryptByKeyAutoAsymKey_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for decryptByKeyAutoAsymKey_AddAuthenticator_Authenticator

Syntax:

DecryptByKeyAutoAsymKey ( akey_ID , akey_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts encrypted data. To do this, it first decrypts a symmetric key with a separate asymmetric key, and then decrypts the encrypted data with the symmetric key extracted in the first "step".

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
CREATE ASYMMETRIC KEY SSN_AKey
    WITH ALGORITHM = RSA_2048 ;
GO
CREATE SYMMETRIC KEY SSN_Key_02 WITH ALGORITHM = DES
    ENCRYPTION BY ASYMMETRIC KEY SSN_AKey;
GO
--
--Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber2 varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber2
    = EncryptByKey(Key_GUID('SSN_Key_02'), NationalIDNumber);
GO
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key.
--2. Decrypt the data.
--3. Close the symmetric key.
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--OPTION TWO, using DecryptByKeyAutoAsymKey()
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoAsymKey ( AsymKey_ID('SSN_AKey') , NULL ,EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

decryptByKeyAutoAsymKey_AddAuthenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

addAuthenticator

-> SExp 

Origin documentation for decryptByKeyAutoAsymKey_AddAuthenticator

Syntax:

DecryptByKeyAutoAsymKey ( akey_ID , akey_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts encrypted data. To do this, it first decrypts a symmetric key with a separate asymmetric key, and then decrypts the encrypted data with the symmetric key extracted in the first "step".

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
CREATE ASYMMETRIC KEY SSN_AKey
    WITH ALGORITHM = RSA_2048 ;
GO
CREATE SYMMETRIC KEY SSN_Key_02 WITH ALGORITHM = DES
    ENCRYPTION BY ASYMMETRIC KEY SSN_AKey;
GO
--
--Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber2 varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber2
    = EncryptByKey(Key_GUID('SSN_Key_02'), NationalIDNumber);
GO
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key.
--2. Decrypt the data.
--3. Close the symmetric key.
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--OPTION TWO, using DecryptByKeyAutoAsymKey()
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoAsymKey ( AsymKey_ID('SSN_AKey') , NULL ,EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

decryptByKeyAutoAsymKey #

Arguments

:: SExp 
-> SExp 
-> SExp

ciphertext

-> SExp 

Origin documentation for decryptByKeyAutoAsymKey

Syntax:

DecryptByKeyAutoAsymKey ( akey_ID , akey_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts encrypted data. To do this, it first decrypts a symmetric key with a separate asymmetric key, and then decrypts the encrypted data with the symmetric key extracted in the first "step".

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdMlk979438teag$$ds987yghn)(*&4fdg^';
CREATE ASYMMETRIC KEY SSN_AKey
    WITH ALGORITHM = RSA_2048 ;
GO
CREATE SYMMETRIC KEY SSN_Key_02 WITH ALGORITHM = DES
    ENCRYPTION BY ASYMMETRIC KEY SSN_AKey;
GO
--
--Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber2 varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber2
    = EncryptByKey(Key_GUID('SSN_Key_02'), NationalIDNumber);
GO
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key.
--2. Decrypt the data.
--3. Close the symmetric key.
OPEN SYMMETRIC KEY SSN_Key_02
   DECRYPTION BY ASYMMETRIC KEY SSN_AKey;
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_02;
--
--OPTION TWO, using DecryptByKeyAutoAsymKey()
SELECT NationalIDNumber, EncryptedNationalIDNumber2
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoAsymKey ( AsymKey_ID('SSN_AKey') , NULL ,EncryptedNationalIDNumber2))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
GO

hasPermsByName_SubSecurable_SubSecurableClass #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

subSecurableClass

-> SExp 

Origin documentation for hasPermsByName_SubSecurable_SubSecurableClass

Syntax:

HAS_PERMS_BY_NAME ( securable , securable_class , permission
    [ , sub-securable ] [ , sub-securable_class ] )

Evaluates the effective permission of the current user on a securable. A related function is fn_my_permissions .

Example:

SELECT HAS_PERMS_BY_NAME(null, null, 'VIEW SERVER STATE');

Example:

SELECT HAS_PERMS_BY_NAME('Ps', 'LOGIN', 'IMPERSONATE');

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');

Example:

EXECUTE AS user = 'Pd'
GO
SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');
GO
REVERT;
GO

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE PROCEDURE')
    & HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_procs,
    HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE TABLE') &
    HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_tables;

Example:

SELECT HAS_PERMS_BY_NAME
(QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name),
    'OBJECT', 'SELECT') AS have_select, * FROM sys.tables

Example:

SELECT HAS_PERMS_BY_NAME('Sales.SalesPerson', 'OBJECT', 'INSERT');

Example:

SELECT HAS_PERMS_BY_NAME('AdventureWorks2012.Sales.SalesPerson',
    'OBJECT', 'INSERT');

Example:

SELECT name AS column_name,
    HAS_PERMS_BY_NAME('T', 'OBJECT', 'SELECT', name, 'COLUMN')
    AS can_select
    FROM sys.columns AS c
    WHERE c.object_id=object_id('T');

hasPermsByName_SubSecurable #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

subSecurable

-> SExp 

Origin documentation for hasPermsByName_SubSecurable

Syntax:

HAS_PERMS_BY_NAME ( securable , securable_class , permission
    [ , sub-securable ] [ , sub-securable_class ] )

Evaluates the effective permission of the current user on a securable. A related function is fn_my_permissions .

Example:

SELECT HAS_PERMS_BY_NAME(null, null, 'VIEW SERVER STATE');

Example:

SELECT HAS_PERMS_BY_NAME('Ps', 'LOGIN', 'IMPERSONATE');

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');

Example:

EXECUTE AS user = 'Pd'
GO
SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');
GO
REVERT;
GO

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE PROCEDURE')
    & HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_procs,
    HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE TABLE') &
    HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_tables;

Example:

SELECT HAS_PERMS_BY_NAME
(QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name),
    'OBJECT', 'SELECT') AS have_select, * FROM sys.tables

Example:

SELECT HAS_PERMS_BY_NAME('Sales.SalesPerson', 'OBJECT', 'INSERT');

Example:

SELECT HAS_PERMS_BY_NAME('AdventureWorks2012.Sales.SalesPerson',
    'OBJECT', 'INSERT');

Example:

SELECT name AS column_name,
    HAS_PERMS_BY_NAME('T', 'OBJECT', 'SELECT', name, 'COLUMN')
    AS can_select
    FROM sys.columns AS c
    WHERE c.object_id=object_id('T');

hasPermsByName #

Arguments

:: SExp 
-> SExp 
-> SExp

permission

-> SExp 

Origin documentation for hasPermsByName

Syntax:

HAS_PERMS_BY_NAME ( securable , securable_class , permission
    [ , sub-securable ] [ , sub-securable_class ] )

Evaluates the effective permission of the current user on a securable. A related function is fn_my_permissions .

Example:

SELECT HAS_PERMS_BY_NAME(null, null, 'VIEW SERVER STATE');

Example:

SELECT HAS_PERMS_BY_NAME('Ps', 'LOGIN', 'IMPERSONATE');

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');

Example:

EXECUTE AS user = 'Pd'
GO
SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'ANY');
GO
REVERT;
GO

Example:

SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE PROCEDURE')
    & HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_procs,
    HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE TABLE') &
    HAS_PERMS_BY_NAME('S', 'SCHEMA', 'ALTER') AS _can_create_tables;

Example:

SELECT HAS_PERMS_BY_NAME
(QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name),
    'OBJECT', 'SELECT') AS have_select, * FROM sys.tables

Example:

SELECT HAS_PERMS_BY_NAME('Sales.SalesPerson', 'OBJECT', 'INSERT');

Example:

SELECT HAS_PERMS_BY_NAME('AdventureWorks2012.Sales.SalesPerson',
    'OBJECT', 'INSERT');

Example:

SELECT name AS column_name,
    HAS_PERMS_BY_NAME('T', 'OBJECT', 'SELECT', name, 'COLUMN')
    AS can_select
    FROM sys.columns AS c
    WHERE c.object_id=object_id('T');

countBig_STAR :: SExp #

Origin documentation for countBig_STAR

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

countBig_Distinctness #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for countBig_Distinctness

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

countBig :: SExp #

Origin documentation for countBig

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

log_Base #

Arguments

:: SExp 
-> SExp

base

-> SExp 

Origin documentation for log_Base

Syntax:

-- Syntax for SQL Server, Azure SQL Database

LOG ( float_expression [, base ] )

Returns the natural logarithm of the specified float expression in SQL Server.

Example:

DECLARE @var FLOAT = 10;
SELECT 'The LOG of the variable is: ' + CONVERT(VARCHAR, LOG(@var));
GO

Example:

SELECT LOG (EXP (10));

Example:

SELECT LOG(10);

log #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for log

Syntax:

-- Syntax for SQL Server, Azure SQL Database

LOG ( float_expression [, base ] )

Returns the natural logarithm of the specified float expression in SQL Server.

Example:

DECLARE @var FLOAT = 10;
SELECT 'The LOG of the variable is: ' + CONVERT(VARCHAR, LOG(@var));
GO

Example:

SELECT LOG (EXP (10));

Example:

SELECT LOG(10);

round_Function #

Arguments

:: SExp 
-> SExp 
-> SExp

function

-> SExp 

Origin documentation for round_Function

Syntax:

ROUND ( numeric_expression , length [ ,function ] )

Returns a numeric value, rounded to the specified length or precision.

Example:

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3);
GO

Example:

SELECT ROUND(150.75, 0);
GO
SELECT ROUND(150.75, 0, 1);
GO

round #

Arguments

:: SExp 
-> SExp

length'

-> SExp 

Origin documentation for round

Syntax:

ROUND ( numeric_expression , length [ ,function ] )

Returns a numeric value, rounded to the specified length or precision.

Example:

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3);
GO

Example:

SELECT ROUND(150.75, 0);
GO
SELECT ROUND(150.75, 0, 1);
GO

denseRank #

Arguments

:: Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for denseRank

Syntax:

DENSE_RANK ( ) OVER ( [ <partition_by_clause> ] < order_by_clause > )

This function returns the rank of each row within a result set partition, with no gaps in the ranking values. The rank of a specific row is one plus the number of distinct rank values that come before that specific row.

Example:

USE AdventureWorks2012;
GO
SELECT i.ProductID, p.Name, i.LocationID, i.Quantity
    ,DENSE_RANK() OVER
    (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank
FROM Production.ProductInventory AS i
INNER JOIN Production.Product AS p
    ON i.ProductID = p.ProductID
WHERE i.LocationID BETWEEN 3 AND 4
ORDER BY i.LocationID;
GO

Example:

USE AdventureWorks2012;
GO
SELECT TOP(10) BusinessEntityID, Rate,
       DENSE_RANK() OVER (ORDER BY Rate DESC) AS RankBySalary
FROM HumanResources.EmployeePayHistory;

Example:

USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
    ,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS "Row Number"
    ,RANK() OVER (ORDER BY a.PostalCode) AS Rank
    ,DENSE_RANK() OVER (ORDER BY a.PostalCode) AS "Dense Rank"
    ,NTILE(4) OVER (ORDER BY a.PostalCode) AS Quartile
    ,s.SalesYTD
    ,a.PostalCode
FROM Sales.SalesPerson AS s
    INNER JOIN Person.Person AS p
        ON s.BusinessEntityID = p.BusinessEntityID
    INNER JOIN Person.Address AS a
        ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0;

Example:

-- Uses AdventureWorks

SELECT LastName, SUM(SalesAmountQuota) AS TotalSales, SalesTerritoryGroup,
    DENSE_RANK() OVER (PARTITION BY SalesTerritoryGroup ORDER BY SUM(SalesAmountQuota) DESC ) AS RankResult
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq ON e.EmployeeKey = sq.EmployeeKey
INNER JOIN dbo.DimSalesTerritory AS st ON e.SalesTerritoryKey = st.SalesTerritoryKey
WHERE SalesPersonFlag = 1 AND SalesTerritoryGroup != N'NA'
GROUP BY LastName, SalesTerritoryGroup;

formatMessage_ParamValue #

Arguments

:: SExp 
-> NonEmpty SExp

paramValue

-> SExp 

Origin documentation for formatMessage_ParamValue

Syntax:

FORMATMESSAGE ( { msg_number  | ' msg_string ' | @msg_variable} , [ param_value [ ,...n ] ] )

Constructs a message from an existing message in sys.messages or from a provided string. The functionality of FORMATMESSAGE resembles that of the RAISERROR statement. However, RAISERROR prints the message immediately, while FORMATMESSAGE returns the formatted message for further processing.

Example:

SELECT text FROM sys.messages WHERE message_id = 20009 AND language_id = 1033;
DECLARE @var1 VARCHAR(200);
SELECT @var1 = FORMATMESSAGE(20009, 'First Variable', 'Second Variable');
SELECT @var1;

Example:

SELECT FORMATMESSAGE('This is the %s and this is the %s.', 'first variable', 'second variable') AS Result;

Example:

SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
SELECT FORMATMESSAGE('Signed int with up to 3 leading zeros %03i', 5);
SELECT FORMATMESSAGE('Signed int with up to 20 leading zeros %020i', 5);
SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
SELECT FORMATMESSAGE('Bigint %I64d', 3000000000);
SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Hello %s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');

formatMessage #

Arguments

:: SExp

msgNumber

-> SExp 

Origin documentation for formatMessage

Syntax:

FORMATMESSAGE ( { msg_number  | ' msg_string ' | @msg_variable} , [ param_value [ ,...n ] ] )

Constructs a message from an existing message in sys.messages or from a provided string. The functionality of FORMATMESSAGE resembles that of the RAISERROR statement. However, RAISERROR prints the message immediately, while FORMATMESSAGE returns the formatted message for further processing.

Example:

SELECT text FROM sys.messages WHERE message_id = 20009 AND language_id = 1033;
DECLARE @var1 VARCHAR(200);
SELECT @var1 = FORMATMESSAGE(20009, 'First Variable', 'Second Variable');
SELECT @var1;

Example:

SELECT FORMATMESSAGE('This is the %s and this is the %s.', 'first variable', 'second variable') AS Result;

Example:

SELECT FORMATMESSAGE('Signed int %i, %d %i, %d, %+i, %+d, %+i, %+d', 5, -5, 50, -50, -11, -11, 11, 11);
SELECT FORMATMESSAGE('Signed int with up to 3 leading zeros %03i', 5);
SELECT FORMATMESSAGE('Signed int with up to 20 leading zeros %020i', 5);
SELECT FORMATMESSAGE('Signed int with leading zero 0 %020i', -55);
SELECT FORMATMESSAGE('Bigint %I64d', 3000000000);
SELECT FORMATMESSAGE('Unsigned int %u, %u', 50, -50);
SELECT FORMATMESSAGE('Unsigned octal %o, %o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal %x, %X, %X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Unsigned octal with prefix: %#o, %#o', 50, -50);
SELECT FORMATMESSAGE('Unsigned hexadecimal with prefix: %#x, %#X, %#X, %X, %x', 11, 11, -11, 50, -50);
SELECT FORMATMESSAGE('Hello %s!', 'TEST');
SELECT FORMATMESSAGE('Hello %20s!', 'TEST');
SELECT FORMATMESSAGE('Hello %-20s!', 'TEST');

eomonth_MonthToAdd #

Arguments

:: SExp 
-> SExp

monthToAdd

-> SExp 

Origin documentation for eomonth_MonthToAdd

Syntax:

EOMONTH ( start_date [, month_to_add ] )

This function returns the last day of the month containing a specified date, with an optional offset.

Example:

DECLARE @date DATETIME = '12/1/2011';
SELECT EOMONTH ( @date ) AS Result;
GO

Example:

DECLARE @date VARCHAR(255) = '12/1/2011';
SELECT EOMONTH ( @date ) AS Result;
GO

Example:

DECLARE @date DATETIME = GETDATE();
SELECT EOMONTH ( @date ) AS 'This Month';
SELECT EOMONTH ( @date, 1 ) AS 'Next Month';
SELECT EOMONTH ( @date, -1 ) AS 'Last Month';
GO

eomonth #

Arguments

:: SExp

startDate

-> SExp 

Origin documentation for eomonth

Syntax:

EOMONTH ( start_date [, month_to_add ] )

This function returns the last day of the month containing a specified date, with an optional offset.

Example:

DECLARE @date DATETIME = '12/1/2011';
SELECT EOMONTH ( @date ) AS Result;
GO

Example:

DECLARE @date VARCHAR(255) = '12/1/2011';
SELECT EOMONTH ( @date ) AS Result;
GO

Example:

DECLARE @date DATETIME = GETDATE();
SELECT EOMONTH ( @date ) AS 'This Month';
SELECT EOMONTH ( @date, 1 ) AS 'Next Month';
SELECT EOMONTH ( @date, -1 ) AS 'Last Month';
GO

charIndex_StartLocation #

Arguments

:: SExp 
-> SExp 
-> SExp

startLocation

-> SExp 

Origin documentation for charIndex_StartLocation

Syntax:

CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )

This function searches for one character expression inside a second character expression, returning the starting position of the first expression if found.

Example:

DECLARE @document VARCHAR(64);
SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('bicycle', @document);
GO

Example:

DECLARE @document VARCHAR(64);

SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('vital', @document, 5);
GO

Example:

DECLARE @document VARCHAR(64);

SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('bike', @document);
GO

Example:

USE tempdb;
GO
--perform a case sensitive search
SELECT CHARINDEX ( 'TEST',
       'This is a Test'
       COLLATE Latin1_General_CS_AS);

Example:

USE tempdb;
GO
SELECT CHARINDEX ( 'Test',
       'This is a Test'
       COLLATE Latin1_General_CS_AS);

Example:

USE tempdb;
GO
SELECT CHARINDEX ( 'TEST',
       'This is a Test'
       COLLATE Latin1_General_CI_AS);
GO

Example:

SELECT CHARINDEX('is', 'This is a string');

Example:

SELECT CHARINDEX('is', 'This is a string', 4);

Example:

SELECT TOP(1) CHARINDEX('at', 'This is a string') FROM dbo.DimCustomer;

charIndex #

Arguments

:: SExp 
-> SExp

expressiontosearch

-> SExp 

Origin documentation for charIndex

Syntax:

CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )

This function searches for one character expression inside a second character expression, returning the starting position of the first expression if found.

Example:

DECLARE @document VARCHAR(64);
SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('bicycle', @document);
GO

Example:

DECLARE @document VARCHAR(64);

SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('vital', @document, 5);
GO

Example:

DECLARE @document VARCHAR(64);

SELECT @document = 'Reflectors are vital safety' +
                   ' components of your bicycle.';
SELECT CHARINDEX('bike', @document);
GO

Example:

USE tempdb;
GO
--perform a case sensitive search
SELECT CHARINDEX ( 'TEST',
       'This is a Test'
       COLLATE Latin1_General_CS_AS);

Example:

USE tempdb;
GO
SELECT CHARINDEX ( 'Test',
       'This is a Test'
       COLLATE Latin1_General_CS_AS);

Example:

USE tempdb;
GO
SELECT CHARINDEX ( 'TEST',
       'This is a Test'
       COLLATE Latin1_General_CI_AS);
GO

Example:

SELECT CHARINDEX('is', 'This is a string');

Example:

SELECT CHARINDEX('is', 'This is a string', 4);

Example:

SELECT TOP(1) CHARINDEX('at', 'This is a string') FROM dbo.DimCustomer;

ntile #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for ntile

Syntax:

NTILE (integer_expression) OVER ( [ <partition_by_clause> ] < order_by_clause > )

Distributes the rows in an ordered partition into a specified number of groups. The groups are numbered, starting at one. For each row, NTILE returns the number of the group to which the row belongs.

Example:

USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
    ,NTILE(4) OVER(ORDER BY SalesYTD DESC) AS Quartile
    ,CONVERT(NVARCHAR(20),s.SalesYTD,1) AS SalesYTD
    , a.PostalCode
FROM Sales.SalesPerson AS s
INNER JOIN Person.Person AS p
    ON s.BusinessEntityID = p.BusinessEntityID
INNER JOIN Person.Address AS a
    ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL
    AND SalesYTD <> 0;
GO

Example:

USE AdventureWorks2012;
GO
DECLARE @NTILE_Var INT = 4;

SELECT p.FirstName, p.LastName
    ,NTILE(@NTILE_Var) OVER(PARTITION BY PostalCode ORDER BY SalesYTD DESC) AS Quartile
    ,CONVERT(NVARCHAR(20),s.SalesYTD,1) AS SalesYTD
    ,a.PostalCode
FROM Sales.SalesPerson AS s
INNER JOIN Person.Person AS p
    ON s.BusinessEntityID = p.BusinessEntityID
INNER JOIN Person.Address AS a
    ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL
    AND SalesYTD <> 0;
GO

Example:

-- Uses AdventureWorks

SELECT e.LastName, NTILE(4) OVER(ORDER BY SUM(SalesAmountQuota) DESC) AS Quartile,
       CONVERT (VARCHAR(13), SUM(SalesAmountQuota), 1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
WHERE sq.CalendarYear = 2003
    AND SalesTerritoryKey IS NOT NULL AND SalesAmountQuota <> 0
GROUP BY e.LastName
ORDER BY Quartile, e.LastName;

Example:

-- Uses AdventureWorks

SELECT e.LastName, NTILE(2) OVER(PARTITION BY e.SalesTerritoryKey ORDER BY SUM(SalesAmountQuota) DESC) AS Quartile,
       CONVERT (VARCHAR(13), SUM(SalesAmountQuota), 1) AS SalesQuota
   ,st.SalesTerritoryCountry
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
INNER JOIN dbo.DimSalesTerritory AS st
    ON e.SalesTerritoryKey = st.SalesTerritoryKey
WHERE sq.CalendarYear = 2003
GROUP BY e.LastName,e.SalesTerritoryKey,st.SalesTerritoryCountry
ORDER BY st.SalesTerritoryCountry, Quartile;

cumeDist #

Arguments

:: Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for cumeDist

Syntax:

CUME_DIST( )
    OVER ( [ partition_by_clause ] order_by_clause )

For SQL Server, this function calculates the cumulative distribution of a value within a group of values. In other words, CUME_DIST calculates the relative position of a specified value in a group of values. Assuming ascending ordering, the CUME_DIST of a value in row r is defined as the number of rows with values less than or equal to that value in row r , divided by the number of rows evaluated in the partition or query result set. CUME_DIST is similar to the PERCENT_RANK function.

Example:

USE AdventureWorks2012;
GO
SELECT Department, LastName, Rate,
       CUME_DIST () OVER (PARTITION BY Department ORDER BY Rate) AS CumeDist,
       PERCENT_RANK() OVER (PARTITION BY Department ORDER BY Rate ) AS PctRank
FROM HumanResources.vEmployeeDepartmentHistory AS edh
    INNER JOIN HumanResources.EmployeePayHistory AS e
    ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN (N'Information Services',N'Document Control')
ORDER BY Department, Rate DESC;

objectName_DatabaseId #

Arguments

:: SExp 
-> SExp

databaseId

-> SExp 

Origin documentation for objectName_DatabaseId

Syntax:

OBJECT_NAME ( object_id [, database_id ] )

Returns the database object name for schema-scoped objects. For a list of schema-scoped objects, see sys.objects (Transact-SQL) .

Example:

USE AdventureWorks2012;
GO
SELECT DISTINCT OBJECT_NAME(object_id)
FROM master.sys.objects;
GO

Example:

USE AdventureWorks2012;
GO
SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id, 1) AS schema_name
FROM master.sys.objects;
GO

Example:

USE AdventureWorks2012;
GO
DECLARE @MyID INT;
SET @MyID = (SELECT OBJECT_ID('AdventureWorks2012.Production.Product',
    'U'));
SELECT name, object_id, type_desc
FROM sys.objects
WHERE name = OBJECT_NAME(@MyID);
GO

Example:

SELECT DB_NAME(st.dbid) AS database_name,
    OBJECT_SCHEMA_NAME(st.objectid, st.dbid) AS schema_name,
    OBJECT_NAME(st.objectid, st.dbid) AS object_name,
    st.text AS query_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE st.objectid IS NOT NULL;
GO

Example:

SELECT QUOTENAME(DB_NAME(database_id))
    + N'.'
    + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id))
    + N'.'
    + QUOTENAME(OBJECT_NAME(object_id, database_id))
    , *
FROM sys.dm_db_index_operational_stats(NULL, NULL, NULL, NULL);
GO

Example:

SELECT name, object_id, type_desc
FROM sys.objects
WHERE name = OBJECT_NAME(274100017);

objectName #

Arguments

:: SExp

objectId'

-> SExp 

Origin documentation for objectName

Syntax:

OBJECT_NAME ( object_id [, database_id ] )

Returns the database object name for schema-scoped objects. For a list of schema-scoped objects, see sys.objects (Transact-SQL) .

Example:

USE AdventureWorks2012;
GO
SELECT DISTINCT OBJECT_NAME(object_id)
FROM master.sys.objects;
GO

Example:

USE AdventureWorks2012;
GO
SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id, 1) AS schema_name
FROM master.sys.objects;
GO

Example:

USE AdventureWorks2012;
GO
DECLARE @MyID INT;
SET @MyID = (SELECT OBJECT_ID('AdventureWorks2012.Production.Product',
    'U'));
SELECT name, object_id, type_desc
FROM sys.objects
WHERE name = OBJECT_NAME(@MyID);
GO

Example:

SELECT DB_NAME(st.dbid) AS database_name,
    OBJECT_SCHEMA_NAME(st.objectid, st.dbid) AS schema_name,
    OBJECT_NAME(st.objectid, st.dbid) AS object_name,
    st.text AS query_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE st.objectid IS NOT NULL;
GO

Example:

SELECT QUOTENAME(DB_NAME(database_id))
    + N'.'
    + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id))
    + N'.'
    + QUOTENAME(OBJECT_NAME(object_id, database_id))
    , *
FROM sys.dm_db_index_operational_stats(NULL, NULL, NULL, NULL);
GO

Example:

SELECT name, object_id, type_desc
FROM sys.objects
WHERE name = OBJECT_NAME(274100017);

suserId_Login #

Arguments

:: SExp

login

-> SExp 

Origin documentation for suserId_Login

Syntax:

SUSER_ID ( [ 'login' ] )

Returns the login identification number of the user.

Note

Starting with SQL Server 2005 (9.x), SUSER_ID returns the value listed as principal_id in the sys.server_principals catalog view.

Example:

SELECT SUSER_ID('sa');

suserId :: SExp #

Origin documentation for suserId

Syntax:

SUSER_ID ( [ 'login' ] )

Returns the login identification number of the user.

Note

Starting with SQL Server 2005 (9.x), SUSER_ID returns the value listed as principal_id in the sys.server_principals catalog view.

Example:

SELECT SUSER_ID('sa');

asymKeyProperty_Sid #

Arguments

:: SExp

sid

-> SExp 

Origin documentation for asymKeyProperty_Sid

Syntax:

ASYMKEYPROPERTY (Key_ID , 'algorithm_desc' | 'string_sid' | 'sid')

This function returns the properties of an asymmetric key.

Example:

SELECT
ASYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm,
ASYMKEYPROPERTY(256, 'string_sid') AS String_SID,
ASYMKEYPROPERTY(256, 'sid') AS SID ;
GO

asymKeyProperty_StringSid #

Arguments

:: SExp

stringSid

-> SExp 

Origin documentation for asymKeyProperty_StringSid

Syntax:

ASYMKEYPROPERTY (Key_ID , 'algorithm_desc' | 'string_sid' | 'sid')

This function returns the properties of an asymmetric key.

Example:

SELECT
ASYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm,
ASYMKEYPROPERTY(256, 'string_sid') AS String_SID,
ASYMKEYPROPERTY(256, 'sid') AS SID ;
GO

asymKeyProperty_KeyId_AlgorithmDesc #

Arguments

:: SExp 
-> SExp

algorithmDesc

-> SExp 

Origin documentation for asymKeyProperty_KeyId_AlgorithmDesc

Syntax:

ASYMKEYPROPERTY (Key_ID , 'algorithm_desc' | 'string_sid' | 'sid')

This function returns the properties of an asymmetric key.

Example:

SELECT
ASYMKEYPROPERTY(256, 'algorithm_desc') AS Algorithm,
ASYMKEYPROPERTY(256, 'string_sid') AS String_SID,
ASYMKEYPROPERTY(256, 'sid') AS SID ;
GO

cryptGenRandom_Seed #

Arguments

:: SExp 
-> SExp

seed

-> SExp 

Origin documentation for cryptGenRandom_Seed

Syntax:

CRYPT_GEN_RANDOM ( length [ , seed ] )

This function returns a cryptographic, randomly-generated number, generated by the Crypto API (CAPI). CRYPT_GEN_RANDOM returns a hexadecimal number with a length of a specified number of bytes.

Example:

SELECT CRYPT_GEN_RANDOM(50) ;

Example:

SELECT CRYPT_GEN_RANDOM(4, 0x25F18060) ;

cryptGenRandom #

Arguments

:: SExp

length'

-> SExp 

Origin documentation for cryptGenRandom

Syntax:

CRYPT_GEN_RANDOM ( length [ , seed ] )

This function returns a cryptographic, randomly-generated number, generated by the Crypto API (CAPI). CRYPT_GEN_RANDOM returns a hexadecimal number with a length of a specified number of bytes.

Example:

SELECT CRYPT_GEN_RANDOM(50) ;

Example:

SELECT CRYPT_GEN_RANDOM(4, 0x25F18060) ;

objectSchemaName_DatabaseId #

Arguments

:: SExp 
-> SExp

databaseId

-> SExp 

Origin documentation for objectSchemaName_DatabaseId

Syntax:

OBJECT_SCHEMA_NAME ( object_id [, database_id ] )

Returns the database schema name for schema-scoped objects. For a list of schema-scoped objects, see sys.objects (Transact-SQL) .

Example:

SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id)
FROM master.sys.objects;

Example:

SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id, 1) AS schema_name
FROM master.sys.objects;

Example:

SELECT DB_NAME(st.dbid) AS database_name,
    OBJECT_SCHEMA_NAME(st.objectid, st.dbid) AS schema_name,
    OBJECT_NAME(st.objectid, st.dbid) AS object_name,
    st.text AS query_statement
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE st.objectid IS NOT NULL;
GO

Example:

SELECT QUOTENAME(DB_NAME(database_id))
    + N'.'
    + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id))
    + N'.'
    + QUOTENAME(OBJECT_NAME(object_id, database_id))
    , *
FROM sys.dm_db_index_operational_stats(null, null, null, null);
GO

objectSchemaName #

Arguments

:: SExp

objectId'

-> SExp 

Origin documentation for objectSchemaName

Syntax:

OBJECT_SCHEMA_NAME ( object_id [, database_id ] )

Returns the database schema name for schema-scoped objects. For a list of schema-scoped objects, see sys.objects (Transact-SQL) .

Example:

SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id)
FROM master.sys.objects;

Example:

SELECT DISTINCT OBJECT_SCHEMA_NAME(object_id, 1) AS schema_name
FROM master.sys.objects;

Example:

SELECT DB_NAME(st.dbid) AS database_name,
    OBJECT_SCHEMA_NAME(st.objectid, st.dbid) AS schema_name,
    OBJECT_NAME(st.objectid, st.dbid) AS object_name,
    st.text AS query_statement
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
WHERE st.objectid IS NOT NULL;
GO

Example:

SELECT QUOTENAME(DB_NAME(database_id))
    + N'.'
    + QUOTENAME(OBJECT_SCHEMA_NAME(object_id, database_id))
    + N'.'
    + QUOTENAME(OBJECT_NAME(object_id, database_id))
    , *
FROM sys.dm_db_index_operational_stats(null, null, null, null);
GO

pwdCompare_Version #

Arguments

:: SExp 
-> SExp 
-> SExp

version'

-> SExp 

Origin documentation for pwdCompare_Version

Syntax:

PWDCOMPARE ( 'clear_text_password'
   , password_hash
   [ , version ] )

Hashes a password and compares the hash to the hash of an existing password. PWDCOMPARE can be used to search for blank SQL Server login passwords or common weak passwords.

Example:

SELECT name FROM sys.sql_logins
WHERE PWDCOMPARE('', password_hash) = 1 ;

Example:

SELECT name FROM sys.sql_logins
WHERE PWDCOMPARE('password', password_hash) = 1 ;

pwdCompare #

Arguments

:: SExp 
-> SExp

passwordHash

-> SExp 

Origin documentation for pwdCompare

Syntax:

PWDCOMPARE ( 'clear_text_password'
   , password_hash
   [ , version ] )

Hashes a password and compares the hash to the hash of an existing password. PWDCOMPARE can be used to search for blank SQL Server login passwords or common weak passwords.

Example:

SELECT name FROM sys.sql_logins
WHERE PWDCOMPARE('', password_hash) = 1 ;

Example:

SELECT name FROM sys.sql_logins
WHERE PWDCOMPARE('password', password_hash) = 1 ;

decryptByAsymKey_AsymKeyPassword #

Arguments

:: SExp 
-> SExp 
-> SExp

asymKeyPassword

-> SExp 

Origin documentation for decryptByAsymKey_AsymKeyPassword

Syntax:

DecryptByAsymKey (Asym_Key_ID , { 'ciphertext' | @ciphertext }
    [ , 'Asym_Key_Password' ] )

This function uses an asymmetric key to decrypt encrypted data.

Example:

SELECT CONVERT(NVARCHAR(max),
    DecryptByAsymKey( AsymKey_Id('JanainaAsymKey02'),
    ProtectedData, N'pGFD4bb925DGvbd2439587y' ))
AS DecryptedData
FROM [AdventureWorks2012].[Sales].[ProtectedData04]
WHERE Description = N'encrypted by asym key''JanainaAsymKey02''';
GO

decryptByAsymKey #

Arguments

:: SExp 
-> SExp

ciphertext

-> SExp 

Origin documentation for decryptByAsymKey

Syntax:

DecryptByAsymKey (Asym_Key_ID , { 'ciphertext' | @ciphertext }
    [ , 'Asym_Key_Password' ] )

This function uses an asymmetric key to decrypt encrypted data.

Example:

SELECT CONVERT(NVARCHAR(max),
    DecryptByAsymKey( AsymKey_Id('JanainaAsymKey02'),
    ProtectedData, N'pGFD4bb925DGvbd2439587y' ))
AS DecryptedData
FROM [AdventureWorks2012].[Sales].[ProtectedData04]
WHERE Description = N'encrypted by asym key''JanainaAsymKey02''';
GO

encryptByPassPhrase_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for encryptByPassPhrase_AddAuthenticator_Authenticator

Syntax:

EncryptByPassPhrase ( { 'passphrase' | @passphrase }
    , { 'cleartext' | @cleartext }
  [ , { add_authenticator | @add_authenticator }
    , { authenticator | @authenticator } ] )

Encrypt data with a passphrase using the TRIPLE DES algorithm with a 128 key bit length.

Note

SQL Server 2017 and later versions encrypts data with a passphrase using an AES256 key.

Example:

USE AdventureWorks2012;
GO
-- Create a column in which to store the encrypted data.
ALTER TABLE Sales.CreditCard
    ADD CardNumber_EncryptedbyPassphrase VARBINARY(256);
GO
-- First get the passphrase from the user.
DECLARE @PassphraseEnteredByUser NVARCHAR(128);
SET @PassphraseEnteredByUser
    = 'A little learning is a dangerous thing!';

-- Update the record for the user's credit card.
-- In this case, the record is number 3681.
UPDATE Sales.CreditCard
SET CardNumber_EncryptedbyPassphrase = EncryptByPassPhrase(@PassphraseEnteredByUser
    , CardNumber, 1, CONVERT(varbinary, CreditCardID))
WHERE CreditCardID = '3681';
GO

encryptByPassPhrase #

Arguments

:: SExp 
-> SExp

cleartext

-> SExp 

Origin documentation for encryptByPassPhrase

Syntax:

EncryptByPassPhrase ( { 'passphrase' | @passphrase }
    , { 'cleartext' | @cleartext }
  [ , { add_authenticator | @add_authenticator }
    , { authenticator | @authenticator } ] )

Encrypt data with a passphrase using the TRIPLE DES algorithm with a 128 key bit length.

Note

SQL Server 2017 and later versions encrypts data with a passphrase using an AES256 key.

Example:

USE AdventureWorks2012;
GO
-- Create a column in which to store the encrypted data.
ALTER TABLE Sales.CreditCard
    ADD CardNumber_EncryptedbyPassphrase VARBINARY(256);
GO
-- First get the passphrase from the user.
DECLARE @PassphraseEnteredByUser NVARCHAR(128);
SET @PassphraseEnteredByUser
    = 'A little learning is a dangerous thing!';

-- Update the record for the user's credit card.
-- In this case, the record is number 3681.
UPDATE Sales.CreditCard
SET CardNumber_EncryptedbyPassphrase = EncryptByPassPhrase(@PassphraseEnteredByUser
    , CardNumber, 1, CONVERT(varbinary, CreditCardID))
WHERE CreditCardID = '3681';
GO

dbId_DatabaseName #

Arguments

:: SExp

databaseName

-> SExp 

Origin documentation for dbId_DatabaseName

Syntax:

DB_ID ( [ 'database_name' ] )

This function returns the database identification (ID) number of a specified database.

Example:

SELECT DB_ID() AS [Database ID];
GO

Example:

SELECT DB_ID(N'AdventureWorks2008R2') AS [Database ID];
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT DB_ID();

Example:

SELECT DB_ID('AdventureWorksPDW2012');

dbId :: SExp #

Origin documentation for dbId

Syntax:

DB_ID ( [ 'database_name' ] )

This function returns the database identification (ID) number of a specified database.

Example:

SELECT DB_ID() AS [Database ID];
GO

Example:

SELECT DB_ID(N'AdventureWorks2008R2') AS [Database ID];
GO

Example:

DECLARE @db_id INT;
DECLARE @object_id INT;
SET @db_id = DB_ID(N'AdventureWorks2012');
SET @object_id = OBJECT_ID(N'AdventureWorks2012.Person.Address');
IF @db_id IS NULL
  BEGIN;
    PRINT N'Invalid database';
  END;
ELSE IF @object_id IS NULL
  BEGIN;
    PRINT N'Invalid object';
  END;
ELSE
  BEGIN;
    SELECT * FROM sys.dm_db_index_operational_stats(@db_id, @object_id, NULL, NULL);
  END;
GO

Example:

SELECT DB_ID();

Example:

SELECT DB_ID('AdventureWorksPDW2012');

str_Length_Decimal #

Arguments

:: SExp 
-> SExp 
-> SExp

decimal

-> SExp 

Origin documentation for str_Length_Decimal

Syntax:

STR ( float_expression [ , length [ , decimal ] ] )

Returns character data converted from numeric data. The character data is right-justified, with a specified length and decimal precision.

Example:

SELECT STR(123.45, 6, 1);
GO

Example:

SELECT STR(123.45, 2, 2);
GO

Example:

SELECT STR (FLOOR (123.45), 8, 3);
GO

str_Length #

Arguments

:: SExp 
-> SExp

length'

-> SExp 

Origin documentation for str_Length

Syntax:

STR ( float_expression [ , length [ , decimal ] ] )

Returns character data converted from numeric data. The character data is right-justified, with a specified length and decimal precision.

Example:

SELECT STR(123.45, 6, 1);
GO

Example:

SELECT STR(123.45, 2, 2);
GO

Example:

SELECT STR (FLOOR (123.45), 8, 3);
GO

str #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for str

Syntax:

STR ( float_expression [ , length [ , decimal ] ] )

Returns character data converted from numeric data. The character data is right-justified, with a specified length and decimal precision.

Example:

SELECT STR(123.45, 6, 1);
GO

Example:

SELECT STR(123.45, 2, 2);
GO

Example:

SELECT STR (FLOOR (123.45), 8, 3);
GO

decryptByKeyAutoCert_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for decryptByKeyAutoCert_AddAuthenticator_Authenticator

Syntax:

DecryptByKeyAutoCert ( cert_ID , cert_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts data with a symmetric key. That symmetric key automatically decrypts with a certificate.

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
CREATE CERTIFICATE HumanResources037
   WITH SUBJECT = 'Sammamish HR',
   EXPIRY_DATE = '10/31/2009';
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = DES
    ENCRYPTION BY CERTIFICATE HumanResources037;
GO
----Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037 ;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO
--
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key
--2. Decrypt the data
--3. Close the symmetric key
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--OPTION TWO, using DecryptByKeyAutoCert()
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoCert ( cert_ID('HumanResources037') , NULL ,EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;

decryptByKeyAutoCert_AddAuthenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

addAuthenticator

-> SExp 

Origin documentation for decryptByKeyAutoCert_AddAuthenticator

Syntax:

DecryptByKeyAutoCert ( cert_ID , cert_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts data with a symmetric key. That symmetric key automatically decrypts with a certificate.

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
CREATE CERTIFICATE HumanResources037
   WITH SUBJECT = 'Sammamish HR',
   EXPIRY_DATE = '10/31/2009';
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = DES
    ENCRYPTION BY CERTIFICATE HumanResources037;
GO
----Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037 ;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO
--
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key
--2. Decrypt the data
--3. Close the symmetric key
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--OPTION TWO, using DecryptByKeyAutoCert()
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoCert ( cert_ID('HumanResources037') , NULL ,EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;

decryptByKeyAutoCert #

Arguments

:: SExp 
-> SExp 
-> SExp

ciphertext

-> SExp 

Origin documentation for decryptByKeyAutoCert

Syntax:

DecryptByKeyAutoCert ( cert_ID , cert_password
    , { 'ciphertext' | @ciphertext }
  [ , { add_authenticator | @add_authenticator }
  [ , { authenticator | @authenticator } ] ] )

This function decrypts data with a symmetric key. That symmetric key automatically decrypts with a certificate.

Example:

--Create the keys and certificate.
USE AdventureWorks2012;
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'mzkvdlk979438teag$$ds987yghn)(*&4fdg^';
CREATE CERTIFICATE HumanResources037
   WITH SUBJECT = 'Sammamish HR',
   EXPIRY_DATE = '10/31/2009';
CREATE SYMMETRIC KEY SSN_Key_01 WITH ALGORITHM = DES
    ENCRYPTION BY CERTIFICATE HumanResources037;
GO
----Add a column of encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128);
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037 ;
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO
--
--Close the key used to encrypt the data.
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--There are two ways to decrypt the stored data.
--
--OPTION ONE, using DecryptByKey()
--1. Open the symmetric key
--2. Decrypt the data
--3. Close the symmetric key
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;
CLOSE SYMMETRIC KEY SSN_Key_01;
--
--OPTION TWO, using DecryptByKeyAutoCert()
SELECT NationalIDNumber, EncryptedNationalIDNumber
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKeyAutoCert ( cert_ID('HumanResources037') , NULL ,EncryptedNationalIDNumber))
    AS 'Decrypted ID Number'
    FROM HumanResources.Employee;

quoteName_QuoteCharacter #

Arguments

:: SExp 
-> SExp

quoteCharacter

-> SExp 

Origin documentation for quoteName_QuoteCharacter

Syntax:

QUOTENAME ( 'character_string' [ , 'quote_character' ] )

Returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.

Example:

SELECT QUOTENAME('abc[]def');

Example:

DECLARE @columnName NVARCHAR(255)='user''s "custom" name'
DECLARE @sql NVARCHAR(MAX) = 'SELECT FirstName AS ' + QUOTENAME(@columnName) + ' FROM dbo.DimCustomer'

EXEC sp_executesql @sql

Example:

SELECT QUOTENAME('abc def');

quoteName #

Arguments

:: SExp

characterString

-> SExp 

Origin documentation for quoteName

Syntax:

QUOTENAME ( 'character_string' [ , 'quote_character' ] )

Returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.

Example:

SELECT QUOTENAME('abc[]def');

Example:

DECLARE @columnName NVARCHAR(255)='user''s "custom" name'
DECLARE @sql NVARCHAR(MAX) = 'SELECT FirstName AS ' + QUOTENAME(@columnName) + ' FROM dbo.DimCustomer'

EXEC sp_executesql @sql

Example:

SELECT QUOTENAME('abc def');

isMember_Role #

Arguments

:: SExp

role'

-> SExp 

Origin documentation for isMember_Role

Syntax:

IS_MEMBER ( { 'group' | 'role' } )

Indicates whether the current user is a member of the specified Microsoft Windows group or SQL Server database role. The IS_MEMBER function is not supported for Azure Active Directory Groups.

Example:

-- Test membership in db_owner and print appropriate message.
IF IS_MEMBER ('db_owner') = 1
   PRINT 'Current user is a member of the db_owner role'
ELSE IF IS_MEMBER ('db_owner') = 0
   PRINT 'Current user is NOT a member of the db_owner role'
ELSE IF IS_MEMBER ('db_owner') IS NULL
   PRINT 'ERROR: Invalid group / role specified';
GO

-- Execute SELECT if user is a member of ADVWORKS\Shipping.
IF IS_MEMBER ('ADVWORKS\Shipping') = 1
   SELECT 'User ' + USER + ' is a member of ADVWORKS\Shipping.';
GO

isMember_Group #

Arguments

:: SExp

group'

-> SExp 

Origin documentation for isMember_Group

Syntax:

IS_MEMBER ( { 'group' | 'role' } )

Indicates whether the current user is a member of the specified Microsoft Windows group or SQL Server database role. The IS_MEMBER function is not supported for Azure Active Directory Groups.

Example:

-- Test membership in db_owner and print appropriate message.
IF IS_MEMBER ('db_owner') = 1
   PRINT 'Current user is a member of the db_owner role'
ELSE IF IS_MEMBER ('db_owner') = 0
   PRINT 'Current user is NOT a member of the db_owner role'
ELSE IF IS_MEMBER ('db_owner') IS NULL
   PRINT 'ERROR: Invalid group / role specified';
GO

-- Execute SELECT if user is a member of ADVWORKS\Shipping.
IF IS_MEMBER ('ADVWORKS\Shipping') = 1
   SELECT 'User ' + USER + ' is a member of ADVWORKS\Shipping.';
GO

isJson_JsonTypeConstraint #

Arguments

:: SExp 
-> SExp

jsonTypeConstraint

-> SExp 

Origin documentation for isJson_JsonTypeConstraint

Syntax:

ISJSON ( expression [, json_type_constraint] )

Tests whether a string contains valid JSON.

Example:

DECLARE @param <data type>
SET @param = <value>

IF (ISJSON(@param) > 0)
BEGIN
     -- Do something with the valid JSON value of @param.
END

Example:

SELECT id, json_col
FROM tab1
WHERE ISJSON(json_col) = 1

Example:

SELECT id, json_col
FROM tab1
WHERE ISJSON(json_col, SCALAR) = 1

Example:

SELECT ISJSON('true', VALUE)

Example:

SELECT ISJSON('test string', VALUE)

Example:

SELECT ISJSON('"test string"', SCALAR)

isJson #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for isJson

Syntax:

ISJSON ( expression [, json_type_constraint] )

Tests whether a string contains valid JSON.

Example:

DECLARE @param <data type>
SET @param = <value>

IF (ISJSON(@param) > 0)
BEGIN
     -- Do something with the valid JSON value of @param.
END

Example:

SELECT id, json_col
FROM tab1
WHERE ISJSON(json_col) = 1

Example:

SELECT id, json_col
FROM tab1
WHERE ISJSON(json_col, SCALAR) = 1

Example:

SELECT ISJSON('true', VALUE)

Example:

SELECT ISJSON('test string', VALUE)

Example:

SELECT ISJSON('"test string"', SCALAR)

userId_User #

Arguments

:: SExp

user'

-> SExp 

Origin documentation for userId_User

Syntax:

USER_ID ( [ 'user' ] )

Returns the identification number for a database user.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use DATABASE_PRINCIPAL_ID instead.

Example:

USE AdventureWorks2012;
SELECT USER_ID('Harold');
GO

userId :: SExp #

Origin documentation for userId

Syntax:

USER_ID ( [ 'user' ] )

Returns the identification number for a database user.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use DATABASE_PRINCIPAL_ID instead.

Example:

USE AdventureWorks2012;
SELECT USER_ID('Harold');
GO

jsonObject #

Arguments

:: [(SExp, SExp)] 
-> Maybe JsonNullStrategy

maybeJsonnullstrategy

-> SExp 

Origin documentation for jsonObject

Syntax:

JSON_OBJECT ( [ <json_key_value> [,...n] ] [ json_null_clause ] )

<json_key_value> ::= json_key_name : value_expression

<json_null_clause> ::=
	  NULL ON NULL
	| ABSENT ON NULL

Constructs JSON object text from zero or more expressions.

Example:

SELECT JSON_OBJECT();

Example:

SELECT JSON_OBJECT('name':'value', 'type':1)

Example:

SELECT JSON_OBJECT('name':'value', 'type':NULL ABSENT ON NULL)

Example:

SELECT JSON_OBJECT('name':'value', 'type':JSON_ARRAY(1, 2))

Example:

SELECT JSON_OBJECT('name':'value', 'type':JSON_OBJECT('type_id':1, 'name':'a'))

Example:

DECLARE @id_key nvarchar(10) = N'id',@id_value nvarchar(64) = NEWID();
SELECT JSON_OBJECT('user_name':USER_NAME(), @id_key:@id_value, 'sid':(SELECT @@SPID))

Example:

SELECT s.session_id, JSON_OBJECT('security_id':s.security_id, 'login':s.login_name, 'status':s.status) as info
FROM sys.dm_exec_sessions AS s
WHERE s.is_user_process = 1;

decryptByCert_CertPassword #

Arguments

:: SExp 
-> SExp 
-> SExp

certPassword

-> SExp 

Origin documentation for decryptByCert_CertPassword

Syntax:

DecryptByCert ( certificate_ID , { 'ciphertext' | @ciphertext }
    [ , { 'cert_password' | @cert_password } ] )

This function uses the private key of a certificate to decrypt encrypted data.

Example:

SELECT CONVERT(NVARCHAR(max), DecryptByCert(Cert_Id('JanainaCert02'),
    ProtectedData, N'pGFD4bb925DGvbd2439587y'))
FROM [AdventureWorks2012].[ProtectedData04]
WHERE Description
    = N'data encrypted by certificate '' JanainaCert02''';
GO

decryptByCert #

Arguments

:: SExp 
-> SExp

ciphertext

-> SExp 

Origin documentation for decryptByCert

Syntax:

DecryptByCert ( certificate_ID , { 'ciphertext' | @ciphertext }
    [ , { 'cert_password' | @cert_password } ] )

This function uses the private key of a certificate to decrypt encrypted data.

Example:

SELECT CONVERT(NVARCHAR(max), DecryptByCert(Cert_Id('JanainaCert02'),
    ProtectedData, N'pGFD4bb925DGvbd2439587y'))
FROM [AdventureWorks2012].[ProtectedData04]
WHERE Description
    = N'data encrypted by certificate '' JanainaCert02''';
GO

indexCol_SchemaName #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

keyId'

-> SExp 

Origin documentation for indexCol_SchemaName

Syntax:

INDEX_COL ( '[ database_name . [ schema_name ] .| schema_name ]
    table_or_view_name', index_id , key_id )

Returns the indexed column name. Returns NULL for XML indexes.

Example:

USE AdventureWorks2012;
GO
SELECT
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,1) AS
        [Index Column 1],
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,2) AS
        [Index Column 2]
;
GO

indexCol_DatabaseName_SchemaName #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

keyId'

-> SExp 

Origin documentation for indexCol_DatabaseName_SchemaName

Syntax:

INDEX_COL ( '[ database_name . [ schema_name ] .| schema_name ]
    table_or_view_name', index_id , key_id )

Returns the indexed column name. Returns NULL for XML indexes.

Example:

USE AdventureWorks2012;
GO
SELECT
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,1) AS
        [Index Column 1],
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,2) AS
        [Index Column 2]
;
GO

indexCol_DatabaseName #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

keyId'

-> SExp 

Origin documentation for indexCol_DatabaseName

Syntax:

INDEX_COL ( '[ database_name . [ schema_name ] .| schema_name ]
    table_or_view_name', index_id , key_id )

Returns the indexed column name. Returns NULL for XML indexes.

Example:

USE AdventureWorks2012;
GO
SELECT
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,1) AS
        [Index Column 1],
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,2) AS
        [Index Column 2]
;
GO

indexCol #

Arguments

:: SExp 
-> SExp 
-> SExp

keyId'

-> SExp 

Origin documentation for indexCol

Syntax:

INDEX_COL ( '[ database_name . [ schema_name ] .| schema_name ]
    table_or_view_name', index_id , key_id )

Returns the indexed column name. Returns NULL for XML indexes.

Example:

USE AdventureWorks2012;
GO
SELECT
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,1) AS
        [Index Column 1],
    INDEX_COL (N'AdventureWorks2012.Sales.SalesOrderDetail', 1,2) AS
        [Index Column 2]
;
GO

signByAsymKey_Password #

Arguments

:: SExp 
-> SExp 
-> SExp

password

-> SExp 

Origin documentation for signByAsymKey_Password

Syntax:

SignByAsymKey( Asym_Key_ID , @plaintext [ , 'password' ] )

Signs plaintext with an asymmetric key

Example:

-- Create a table in which to store the data
CREATE TABLE [SignedData04](Description NVARCHAR(max), Data NVARCHAR(max), DataSignature VARBINARY(8000));
GO
-- Store data together with its signature
DECLARE @clear_text_data NVARCHAR(max);
set @clear_text_data = N'Important numbers 2, 3, 5, 7, 11, 13, 17,
      19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
      83, 89, 97';
INSERT INTO [SignedData04]
    VALUES( N'data encrypted by asymmetric key ''PrimeKey''',
    @clear_text_data, SignByAsymKey( AsymKey_Id( 'PrimeKey' ),
    @clear_text_data, N'pGFD4bb925DGvbd2439587y' ));
GO

signByAsymKey #

Arguments

:: SExp 
-> SExp

plaintext

-> SExp 

Origin documentation for signByAsymKey

Syntax:

SignByAsymKey( Asym_Key_ID , @plaintext [ , 'password' ] )

Signs plaintext with an asymmetric key

Example:

-- Create a table in which to store the data
CREATE TABLE [SignedData04](Description NVARCHAR(max), Data NVARCHAR(max), DataSignature VARBINARY(8000));
GO
-- Store data together with its signature
DECLARE @clear_text_data NVARCHAR(max);
set @clear_text_data = N'Important numbers 2, 3, 5, 7, 11, 13, 17,
      19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79,
      83, 89, 97';
INSERT INTO [SignedData04]
    VALUES( N'data encrypted by asymmetric key ''PrimeKey''',
    @clear_text_data, SignByAsymKey( AsymKey_Id( 'PrimeKey' ),
    @clear_text_data, N'pGFD4bb925DGvbd2439587y' ));
GO

tryConvert_Length_Style #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

style

-> SExp 

Origin documentation for tryConvert_Length_Style

Syntax:

TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

Example:

SELECT TRY_CONVERT(xml, 4) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

tryConvert_Length #

Arguments

:: SExp 
-> SExp 
-> SExp

expression

-> SExp 

Origin documentation for tryConvert_Length

Syntax:

TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

Example:

SELECT TRY_CONVERT(xml, 4) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

tryConvert_Style #

Arguments

:: SExp 
-> SExp 
-> SExp

style

-> SExp 

Origin documentation for tryConvert_Style

Syntax:

TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

Example:

SELECT TRY_CONVERT(xml, 4) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

tryConvert #

Arguments

:: SExp 
-> SExp

expression

-> SExp 

Origin documentation for tryConvert

Syntax:

TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Example:

SELECT
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;
GO

Example:

SET DATEFORMAT dmy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

Example:

SELECT TRY_CONVERT(xml, 4) AS Result;
GO

Example:

SET DATEFORMAT mdy;
SELECT TRY_CONVERT(datetime2, '12/31/2010') AS Result;
GO

getAnsiNull_Database #

Arguments

:: SExp

database

-> SExp 

Origin documentation for getAnsiNull_Database

Syntax:

GETANSINULL ( [ 'database' ] )

Returns the default nullability for the database for this session.

Example:

USE AdventureWorks2012;
GO
SELECT GETANSINULL('AdventureWorks2012')
GO

getAnsiNull :: SExp #

Origin documentation for getAnsiNull

Syntax:

GETANSINULL ( [ 'database' ] )

Returns the default nullability for the database for this session.

Example:

USE AdventureWorks2012;
GO
SELECT GETANSINULL('AdventureWorks2012')
GO

triggerNestLevel_ObjectId_TriggerType_TriggerEventCategory #

Arguments

:: SExp 
-> SExp 
-> SExp

triggerEventCategory

-> SExp 

Origin documentation for triggerNestLevel_ObjectId_TriggerType_TriggerEventCategory

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

triggerNestLevel_ObjectId_TriggerType #

Arguments

:: SExp 
-> SExp

triggerType

-> SExp 

Origin documentation for triggerNestLevel_ObjectId_TriggerType

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

triggerNestLevel_ObjectId #

Arguments

:: SExp

objectId'

-> SExp 

Origin documentation for triggerNestLevel_ObjectId

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

triggerNestLevel_TriggerType_TriggerEventCategory #

Arguments

:: SExp 
-> SExp

triggerEventCategory

-> SExp 

Origin documentation for triggerNestLevel_TriggerType_TriggerEventCategory

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

triggerNestLevel_TriggerType #

Arguments

:: SExp

triggerType

-> SExp 

Origin documentation for triggerNestLevel_TriggerType

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

triggerNestLevel :: SExp #

Origin documentation for triggerNestLevel

Syntax:

TRIGGER_NESTLEVEL ( [ object_id ] , [ 'trigger_type' ] , [ 'trigger_event_category' ] )

Returns the number of triggers executed for the statement that fired the trigger. TRIGGER_NESTLEVEL is used in DML and DDL triggers to determine the current level of nesting.

Example:

IF ( (SELECT TRIGGER_NESTLEVEL( OBJECT_ID('xyz') , 'AFTER' , 'DML' ) ) > 5 )
   RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

Example:

IF ( ( SELECT TRIGGER_NESTLEVEL ( ( SELECT object_id FROM sys.triggers
WHERE name = 'abc' ), 'AFTER' , 'DDL' ) ) > 5 )
   RAISERROR ('Trigger abc nested more than 5 levels.',16,-1)

Example:

IF ( (SELECT trigger_nestlevel() ) > 5 )
   RAISERROR
      ('This statement nested over 5 levels of triggers.',16,-1)

jsonQuery_Path #

Arguments

:: SExp 
-> SExp

path

-> SExp 

Origin documentation for jsonQuery_Path

Syntax:

JSON_QUERY ( expression [ , path ] )

Extracts an object or an array from a JSON string.

To extract a scalar value from a JSON string instead of an object or an array, see JSON_VALUE (Transact-SQL) . For info about the differences between JSON_VALUE and JSON_QUERY , see Compare JSON_VALUE and JSON_QUERY .

Example:

SELECT PersonID,FullName,
  JSON_QUERY(CustomFields,'$.OtherLanguages') AS Languages
FROM Application.People

Example:

SELECT StockItemID, StockItemName,
         JSON_QUERY(Tags) as Tags,
         JSON_QUERY(CONCAT('["',ValidFrom,'","',ValidTo,'"]')) ValidityPeriod
FROM Warehouse.StockItems
FOR JSON PATH

jsonQuery #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for jsonQuery

Syntax:

JSON_QUERY ( expression [ , path ] )

Extracts an object or an array from a JSON string.

To extract a scalar value from a JSON string instead of an object or an array, see JSON_VALUE (Transact-SQL) . For info about the differences between JSON_VALUE and JSON_QUERY , see Compare JSON_VALUE and JSON_QUERY .

Example:

SELECT PersonID,FullName,
  JSON_QUERY(CustomFields,'$.OtherLanguages') AS Languages
FROM Application.People

Example:

SELECT StockItemID, StockItemName,
         JSON_QUERY(Tags) as Tags,
         JSON_QUERY(CONCAT('["',ValidFrom,'","',ValidTo,'"]')) ValidityPeriod
FROM Warehouse.StockItems
FOR JSON PATH

lead_Offset_Default #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lead_Offset_Default

Syntax:

LEAD ( scalar_expression [ ,offset ] , [ default ] )
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
    LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LEAD (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS NextRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LEAD(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS NextQuota,
   SalesAmountQuota - LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001,2002)
ORDER BY CalendarYear, CalendarQuarter;

lead_Offset #

Arguments

:: SExp 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lead_Offset

Syntax:

LEAD ( scalar_expression [ ,offset ] , [ default ] )
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
    LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LEAD (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS NextRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LEAD(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS NextQuota,
   SalesAmountQuota - LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001,2002)
ORDER BY CalendarYear, CalendarQuarter;

lead_Default #

Arguments

:: SExp 
-> SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lead_Default

Syntax:

LEAD ( scalar_expression [ ,offset ] , [ default ] )
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
    LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LEAD (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS NextRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LEAD(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS NextQuota,
   SalesAmountQuota - LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001,2002)
ORDER BY CalendarYear, CalendarQuarter;

lead #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for lead

Syntax:

LEAD ( scalar_expression [ ,offset ] , [ default ] )
    OVER ( [ partition_by_clause ] order_by_clause )

Accesses data from a subsequent row in the same result set without the use of a self-join starting with SQL Server 2012 (11.x). LEAD provides access to a row at a given physical offset that follows the current row. Use this analytic function in a SELECT statement to compare values in the current row with values in a following row.

Example:

USE AdventureWorks2012;
GO
SELECT BusinessEntityID, YEAR(QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota,
    LEAD(SalesQuota, 1,0) OVER (ORDER BY YEAR(QuotaDate)) AS NextQuota
FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID = 275 AND YEAR(QuotaDate) IN ('2005','2006');

Example:

USE AdventureWorks2012;
GO
SELECT TerritoryName, BusinessEntityID, SalesYTD,
       LEAD (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS NextRepSales
FROM Sales.vSalesPerson
WHERE TerritoryName IN (N'Northwest', N'Canada')
ORDER BY TerritoryName;

Example:

CREATE TABLE T (a INT, b INT, c INT);
GO
INSERT INTO T VALUES (1, 1, -3), (2, 2, 4), (3, 1, NULL), (4, 3, 1), (5, 2, NULL), (6, 1, 5);

SELECT b, c,
    LEAD(2*c, b*(SELECT MIN(b) FROM T), -c/2.0) OVER (ORDER BY a) AS i
FROM T;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS NextQuota,
   SalesAmountQuota - LEAD(SalesAmountQuota,1,0) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Diff
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear IN (2001,2002)
ORDER BY CalendarYear, CalendarQuarter;

rand_Seed #

Arguments

:: SExp

seed

-> SExp 

Origin documentation for rand_Seed

Syntax:

RAND ( [ seed ] )

Returns a pseudo-random float value from 0 through 1, exclusive.

Example:

SELECT RAND(100), RAND(), RAND()

Example:

DECLARE @counter SMALLINT;
SET @counter = 1;
WHILE @counter < 5
   BEGIN
      SELECT RAND() Random_Number
      SET @counter = @counter + 1
   END;
GO

rand :: SExp #

Origin documentation for rand

Syntax:

RAND ( [ seed ] )

Returns a pseudo-random float value from 0 through 1, exclusive.

Example:

SELECT RAND(100), RAND(), RAND()

Example:

DECLARE @counter SMALLINT;
SET @counter = 1;
WHILE @counter < 5
   BEGIN
      SELECT RAND() Random_Number
      SET @counter = @counter + 1
   END;
GO

dateBucket_Origin #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

origin

-> SExp 

Origin documentation for dateBucket_Origin

Syntax:

DATE_BUCKET (datepart, number, date [, origin ] )

This function returns the date-time value corresponding to the start of each date-time bucket from the timestamp defined by the origin parameter, or the default origin value of 1900-01-01 00:00:00.000 if the origin parameter isn't specified.

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 1, @date);

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 2, @date);
SELECT DATE_BUCKET(WEEK, 3, @date);
SELECT DATE_BUCKET(WEEK, 4, @date);
SELECT DATE_BUCKET(WEEK, 6, @date);

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 5, @date);

Example:

DECLARE @date DATETIME2 = '2020-06-15 21:22:11';
DECLARE @origin DATETIME2 = '2019-01-01 00:00:00';
SELECT DATE_BUCKET(WEEK, 5, @date, @origin);

Example:

DECLARE @date DATETIME2 = '2020-04-30 00:00:00';
SELECT DATE_BUCKET(DAY, 2147483648, @date);

Example:

SELECT DATE_BUCKET(DAY, 10, SYSUTCDATETIME());

Example:

DECLARE @date DATETIME2 = '2020-04-30 21:21:21';
SELECT 'Week', DATE_BUCKET(WEEK, 1, @date)
UNION ALL
SELECT 'Day', DATE_BUCKET(DAY, 1, @date)
UNION ALL
SELECT 'Hour', DATE_BUCKET(HOUR, 1, @date)
UNION ALL
SELECT 'Minutes', DATE_BUCKET(MINUTE, 1, @date)
UNION ALL
SELECT 'Seconds', DATE_BUCKET(SECOND, 1, @date);

Example:

DECLARE @days INT = 365,
    @datetime DATETIME2 = '2000-01-01 01:01:01.1110000';
    /* 2000 was a leap year */;
SELECT DATE_BUCKET(DAY, @days, @datetime);

Example:

SELECT DATE_BUCKET(WEEK, 1, CAST(ShipDate AS DATETIME2)) AS ShippedDateBucket
    , SUM(OrderQuantity) AS SumOrderQuantity
    , SUM(UnitPrice) AS SumUnitPrice
FROM dbo.FactInternetSales FIS
WHERE ShipDate BETWEEN '2011-01-03 00:00:00.000'
        AND '2011-02-28 00:00:00.000'
GROUP BY DATE_BUCKET(WEEK, 1, CAST(ShipDate AS DATETIME2))
ORDER BY ShippedDateBucket;

Example:

SELECT DATE_BUCKET(WEEK, 10, SYSDATETIME());

Example:

SELECT DATE_BUCKET(WEEK, (
    SELECT TOP 1 CustomerKey
    FROM dbo.DimCustomer
    WHERE GeographyKey > 100
    ), (
    SELECT MAX(OrderDate)
    FROM dbo.FactInternetSales
));

Example:

SELECT DATE_BUCKET(WEEK, (10/2), SYSDATETIME());

Example:

SELECT DISTINCT DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2)) AS DateBucket
    , FIRST_VALUE([SalesOrderNumber]) OVER (
        ORDER BY DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2))
        ) AS First_Value_In_Bucket
    , LAST_VALUE([SalesOrderNumber]) OVER (
        ORDER BY DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2))
        ) AS Last_Value_In_Bucket
FROM [dbo].[FactInternetSales]
WHERE ShipDate BETWEEN '2011-01-03 00:00:00.000'
        AND '2011-02-28 00:00:00.000'
ORDER BY DateBucket;
GO

Example:

DECLARE @date DATETIME2 = '2020-06-15 21:22:11';
DECLARE @origin DATETIME2 = '2019-01-01 00:00:00';
SELECT DATE_BUCKET(HOUR, 2, @date, @origin);

dateBucket #

Arguments

:: SExp 
-> SExp 
-> SExp

date

-> SExp 

Origin documentation for dateBucket

Syntax:

DATE_BUCKET (datepart, number, date [, origin ] )

This function returns the date-time value corresponding to the start of each date-time bucket from the timestamp defined by the origin parameter, or the default origin value of 1900-01-01 00:00:00.000 if the origin parameter isn't specified.

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 1, @date);

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 2, @date);
SELECT DATE_BUCKET(WEEK, 3, @date);
SELECT DATE_BUCKET(WEEK, 4, @date);
SELECT DATE_BUCKET(WEEK, 6, @date);

Example:

DECLARE @date DATETIME2 = '2020-04-15 21:22:11';
SELECT DATE_BUCKET(WEEK, 5, @date);

Example:

DECLARE @date DATETIME2 = '2020-06-15 21:22:11';
DECLARE @origin DATETIME2 = '2019-01-01 00:00:00';
SELECT DATE_BUCKET(WEEK, 5, @date, @origin);

Example:

DECLARE @date DATETIME2 = '2020-04-30 00:00:00';
SELECT DATE_BUCKET(DAY, 2147483648, @date);

Example:

SELECT DATE_BUCKET(DAY, 10, SYSUTCDATETIME());

Example:

DECLARE @date DATETIME2 = '2020-04-30 21:21:21';
SELECT 'Week', DATE_BUCKET(WEEK, 1, @date)
UNION ALL
SELECT 'Day', DATE_BUCKET(DAY, 1, @date)
UNION ALL
SELECT 'Hour', DATE_BUCKET(HOUR, 1, @date)
UNION ALL
SELECT 'Minutes', DATE_BUCKET(MINUTE, 1, @date)
UNION ALL
SELECT 'Seconds', DATE_BUCKET(SECOND, 1, @date);

Example:

DECLARE @days INT = 365,
    @datetime DATETIME2 = '2000-01-01 01:01:01.1110000';
    /* 2000 was a leap year */;
SELECT DATE_BUCKET(DAY, @days, @datetime);

Example:

SELECT DATE_BUCKET(WEEK, 1, CAST(ShipDate AS DATETIME2)) AS ShippedDateBucket
    , SUM(OrderQuantity) AS SumOrderQuantity
    , SUM(UnitPrice) AS SumUnitPrice
FROM dbo.FactInternetSales FIS
WHERE ShipDate BETWEEN '2011-01-03 00:00:00.000'
        AND '2011-02-28 00:00:00.000'
GROUP BY DATE_BUCKET(WEEK, 1, CAST(ShipDate AS DATETIME2))
ORDER BY ShippedDateBucket;

Example:

SELECT DATE_BUCKET(WEEK, 10, SYSDATETIME());

Example:

SELECT DATE_BUCKET(WEEK, (
    SELECT TOP 1 CustomerKey
    FROM dbo.DimCustomer
    WHERE GeographyKey > 100
    ), (
    SELECT MAX(OrderDate)
    FROM dbo.FactInternetSales
));

Example:

SELECT DATE_BUCKET(WEEK, (10/2), SYSDATETIME());

Example:

SELECT DISTINCT DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2)) AS DateBucket
    , FIRST_VALUE([SalesOrderNumber]) OVER (
        ORDER BY DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2))
        ) AS First_Value_In_Bucket
    , LAST_VALUE([SalesOrderNumber]) OVER (
        ORDER BY DATE_BUCKET(DAY, 30, CAST([ShipDate] AS DATETIME2))
        ) AS Last_Value_In_Bucket
FROM [dbo].[FactInternetSales]
WHERE ShipDate BETWEEN '2011-01-03 00:00:00.000'
        AND '2011-02-28 00:00:00.000'
ORDER BY DateBucket;
GO

Example:

DECLARE @date DATETIME2 = '2020-06-15 21:22:11';
DECLARE @origin DATETIME2 = '2019-01-01 00:00:00';
SELECT DATE_BUCKET(HOUR, 2, @date, @origin);

isRoleMember_DatabasePrincipal #

Arguments

:: SExp 
-> SExp

databasePrincipal

-> SExp 

Origin documentation for isRoleMember_DatabasePrincipal

Syntax:

IS_ROLEMEMBER ( 'role' [ , 'database_principal' ] )

Indicates whether a specified database principal is a member of the specified database role.

Example:

IF IS_ROLEMEMBER ('db_datareader') = 1
   print 'Current user is a member of the db_datareader role'
ELSE IF IS_ROLEMEMBER ('db_datareader') = 0
   print 'Current user is NOT a member of the db_datareader role'
ELSE IF IS_ROLEMEMBER ('db_datareader') IS NULL
   print 'ERROR: The database role specified is not valid.';

isRoleMember #

Arguments

:: SExp

role'

-> SExp 

Origin documentation for isRoleMember

Syntax:

IS_ROLEMEMBER ( 'role' [ , 'database_principal' ] )

Indicates whether a specified database principal is a member of the specified database role.

Example:

IF IS_ROLEMEMBER ('db_datareader') = 1
   print 'Current user is a member of the db_datareader role'
ELSE IF IS_ROLEMEMBER ('db_datareader') = 0
   print 'Current user is NOT a member of the db_datareader role'
ELSE IF IS_ROLEMEMBER ('db_datareader') IS NULL
   print 'ERROR: The database role specified is not valid.';

encryptByKey_AddAuthenticator_Authenticator #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

authenticator

-> SExp 

Origin documentation for encryptByKey_AddAuthenticator_Authenticator

Syntax:

EncryptByKey ( key_GUID , { 'cleartext' | @cleartext }
    [, { add_authenticator | @add_authenticator }
     , { authenticator | @authenticator } ] )

Encrypts data by using a symmetric key.

Note

This syntax is not supported by serverless SQL pool in Azure Synapse Analytics.

Example:

USE AdventureWorks2012;
GO

-- Create a column in which to store the encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128);
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;

-- Encrypt the value in column NationalIDNumber with symmetric key
-- SSN_Key_01. Save the result in column EncryptedNationalIDNumber.
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO

Example:

USE AdventureWorks2012;

-- Create a column in which to store the encrypted data.
ALTER TABLE Sales.CreditCard
    ADD CardNumber_Encrypted varbinary(128);
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY CreditCards_Key11
    DECRYPTION BY CERTIFICATE Sales09;

-- Encrypt the value in column CardNumber with symmetric
-- key CreditCards_Key11.
-- Save the result in column CardNumber_Encrypted.
UPDATE Sales.CreditCard
SET CardNumber_Encrypted = EncryptByKey(Key_GUID('CreditCards_Key11'),
    CardNumber, 1, CONVERT( varbinary, CreditCardID) );
GO

encryptByKey #

Arguments

:: SExp 
-> SExp

cleartext

-> SExp 

Origin documentation for encryptByKey

Syntax:

EncryptByKey ( key_GUID , { 'cleartext' | @cleartext }
    [, { add_authenticator | @add_authenticator }
     , { authenticator | @authenticator } ] )

Encrypts data by using a symmetric key.

Note

This syntax is not supported by serverless SQL pool in Azure Synapse Analytics.

Example:

USE AdventureWorks2012;
GO

-- Create a column in which to store the encrypted data.
ALTER TABLE HumanResources.Employee
    ADD EncryptedNationalIDNumber varbinary(128);
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE HumanResources037;

-- Encrypt the value in column NationalIDNumber with symmetric key
-- SSN_Key_01. Save the result in column EncryptedNationalIDNumber.
UPDATE HumanResources.Employee
SET EncryptedNationalIDNumber
    = EncryptByKey(Key_GUID('SSN_Key_01'), NationalIDNumber);
GO

Example:

USE AdventureWorks2012;

-- Create a column in which to store the encrypted data.
ALTER TABLE Sales.CreditCard
    ADD CardNumber_Encrypted varbinary(128);
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY CreditCards_Key11
    DECRYPTION BY CERTIFICATE Sales09;

-- Encrypt the value in column CardNumber with symmetric
-- key CreditCards_Key11.
-- Save the result in column CardNumber_Encrypted.
UPDATE Sales.CreditCard
SET CardNumber_Encrypted = EncryptByKey(Key_GUID('CreditCards_Key11'),
    CardNumber, 1, CONVERT( varbinary, CreditCardID) );
GO

userName_Id #

Arguments

:: SExp

id'

-> SExp 

Origin documentation for userName_Id

Syntax:

USER_NAME ( [ id ] )

Returns a database user name from a specified identification number.

Example:

SELECT USER_NAME(13);
GO

Example:

SELECT USER_NAME();
GO

Example:

SELECT name FROM sysusers WHERE name = USER_NAME(1);
GO

Example:

SELECT USER_NAME();
GO
EXECUTE AS USER = 'Zelig';
GO
SELECT USER_NAME();
GO
REVERT;
GO
SELECT USER_NAME();
GO

Example:

SELECT USER_NAME();

Example:

SELECT name FROM sysusers WHERE name = USER_NAME(1);

userName :: SExp #

Origin documentation for userName

Syntax:

USER_NAME ( [ id ] )

Returns a database user name from a specified identification number.

Example:

SELECT USER_NAME(13);
GO

Example:

SELECT USER_NAME();
GO

Example:

SELECT name FROM sysusers WHERE name = USER_NAME(1);
GO

Example:

SELECT USER_NAME();
GO
EXECUTE AS USER = 'Zelig';
GO
SELECT USER_NAME();
GO
REVERT;
GO
SELECT USER_NAME();
GO

Example:

SELECT USER_NAME();

Example:

SELECT name FROM sysusers WHERE name = USER_NAME(1);

schemaName_SchemaId #

Arguments

:: SExp

schemaId'

-> SExp 

Origin documentation for schemaName_SchemaId

Syntax:

SCHEMA_NAME ( [ schema_id ] )

Returns the schema name associated with a schema ID.

Example:

SELECT SCHEMA_NAME();

Example:

SELECT SCHEMA_NAME(1);

schemaName :: SExp #

Origin documentation for schemaName

Syntax:

SCHEMA_NAME ( [ schema_id ] )

Returns the schema name associated with a schema ID.

Example:

SELECT SCHEMA_NAME();

Example:

SELECT SCHEMA_NAME(1);

certprivateKey_DecryptionPassword #

Arguments

:: SExp 
-> SExp 
-> SExp

decryptionPassword

-> SExp 

Origin documentation for certprivateKey_DecryptionPassword

Syntax:

CERTPRIVATEKEY
    (
          cert_ID
        , ' encryption_password '
      [ , ' decryption_password ' ]
    )

This function returns the private key of a certificate in binary format. This function takes three arguments.

Only users with access to the certificate private key can use this function. This function returns the private key in PVK format.

Example:

CREATE DATABASE TEST1;
GO
USE TEST1
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Use 5tr0ng P^55Words'
GO
CREATE CERTIFICATE Shipping04
WITH SUBJECT = 'Sammamish Shipping Records',
EXPIRY_DATE = '20401031';
GO
SELECT CERTPRIVATEKEY(CERT_ID('Shipping04'), 'jklalkaa/; uia3dd');

certprivateKey #

Arguments

:: SExp 
-> SExp

encryptionPassword

-> SExp 

Origin documentation for certprivateKey

Syntax:

CERTPRIVATEKEY
    (
          cert_ID
        , ' encryption_password '
      [ , ' decryption_password ' ]
    )

This function returns the private key of a certificate in binary format. This function takes three arguments.

Only users with access to the certificate private key can use this function. This function returns the private key in PVK format.

Example:

CREATE DATABASE TEST1;
GO
USE TEST1
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Use 5tr0ng P^55Words'
GO
CREATE CERTIFICATE Shipping04
WITH SUBJECT = 'Sammamish Shipping Records',
EXPIRY_DATE = '20401031';
GO
SELECT CERTPRIVATEKEY(CERT_ID('Shipping04'), 'jklalkaa/; uia3dd');

trim_BOTH_FROM #

Arguments

:: SExp 
-> SExp

string

-> SExp 

Origin documentation for trim_BOTH_FROM

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_BOTH #

Arguments

:: SExp

string

-> SExp 

Origin documentation for trim_BOTH

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_TRAILING_FROM #

Arguments

:: SExp 
-> SExp

string

-> SExp 

Origin documentation for trim_TRAILING_FROM

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_TRAILING #

Arguments

:: SExp

string

-> SExp 

Origin documentation for trim_TRAILING

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_LEADING_FROM #

Arguments

:: SExp 
-> SExp

string

-> SExp 

Origin documentation for trim_LEADING_FROM

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_LEADING #

Arguments

:: SExp

string

-> SExp 

Origin documentation for trim_LEADING

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim_FROM #

Arguments

:: SExp 
-> SExp

string

-> SExp 

Origin documentation for trim_FROM

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

trim #

Arguments

:: SExp

string

-> SExp 

Origin documentation for trim

Syntax:

TRIM ( [ LEADING | TRAILING | BOTH ] [characters FROM ] string )

Removes the space character char(32) or other specified characters from the start and end of a string.

Starting with SQL Server 2022 (16.x), optionally remove the space character char(32) or other specified characters from the start, end, or both sides of a string.

Example:

SELECT TRIM( '     test    ') AS Result;

Example:

SELECT TRIM( '.,! ' FROM '     #     test    .') AS Result;

Example:

SELECT TRIM(LEADING '.,! ' FROM  '     .#     test    .') AS Result;

Example:

SELECT TRIM(TRAILING '.,! ' FROM '     .#     test    .') AS Result;

Example:

SELECT TRIM(BOTH '123' FROM '123abc123') AS Result;

setBit #

Arguments

:: SExp 
-> SExp 
-> SExp

bitValue

-> SExp 

Origin documentation for setBit

Syntax:

SET_BIT ( expression_value, bit_offset )
SET_BIT ( expression_value, bit_offset, bit_value )

SET_BIT returns expression_value offset by the bit defined by bit_offset . The bit value defaults to 1, or is set by bit_value .

Example:

SELECT SET_BIT ( 0x00, 2 ) as VARBIN1;

Example:

SELECT SET_BIT ( 0xabcdef, 0, 0 ) as VARBIN2;

acos #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for acos

Syntax:

ACOS ( float_expression )

A function that returns the angle, in radians, whose cosine is the specified float expression. This is also called arccosine.

Example:

SET NOCOUNT OFF;
DECLARE @cos FLOAT;
SET @cos = -1.0;
SELECT 'The ACOS of the number is: ' + CONVERT(VARCHAR, ACOS(@cos));

Example:

---------------------------------
The ACOS of the number is: 3.14159

(1 row(s) affected)

hostName :: SExp #

Origin documentation for hostName

Syntax:

HOST_NAME ()

Returns the workstation name.

Example:

CREATE TABLE Orders
   (OrderID     INT        PRIMARY KEY,
    CustomerID  NCHAR(5)   REFERENCES Customers(CustomerID),
    Workstation NCHAR(30)  NOT NULL DEFAULT HOST_NAME(),
    OrderDate   DATETIME   NOT NULL,
    ShipDate    DATETIME   NULL,
    ShipperID   INT        NULL REFERENCES Shippers(ShipperID));
GO

radians #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for radians

Syntax:

RADIANS ( numeric_expression )

Returns radians when a numeric expression, in degrees, is entered.

Example:

SELECT RADIANS(1e-307)
GO

Example:

-- First value is -45.01.
DECLARE @angle FLOAT
SET @angle = -45.01
SELECT 'The RADIANS of the angle is: ' +
   CONVERT(VARCHAR, RADIANS(@angle))
GO
-- Next value is -181.01.
DECLARE @angle FLOAT
SET @angle = -181.01
SELECT 'The RADIANS of the angle is: ' +
   CONVERT(VARCHAR, RADIANS(@angle))
GO
-- Next value is 0.00.
DECLARE @angle FLOAT
SET @angle = 0.00
SELECT 'The RADIANS of the angle is: ' +
   CONVERT(VARCHAR, RADIANS(@angle))
GO
-- Next value is 0.1472738.
DECLARE @angle FLOAT
SET @angle = 0.1472738
SELECT 'The RADIANS of the angle is: ' +
    CONVERT(VARCHAR, RADIANS(@angle))
GO
-- Last value is 197.1099392.
DECLARE @angle FLOAT
SET @angle = 197.1099392
SELECT 'The RADIANS of the angle is: ' +
   CONVERT(VARCHAR, RADIANS(@angle))
GO

textvalid #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

ptr

-> SExp 

Origin documentation for textvalid

Syntax:

TEXTVALID ( 'table.column' ,text_ ptr )

A text , ntext , or image function that checks whether a specific text pointer is valid.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Alternative functionality is not available.

Example:

USE pubs;
GO
SELECT pub_id, 'Valid (if 1) Text data'
   = TEXTVALID ('pub_info.logo', TEXTPTR(logo))
FROM pub_info
ORDER BY pub_id;
GO

ltrim #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for ltrim

Syntax:

LTRIM ( character_expression )

Returns a character string after truncating all leading spaces.

Removes space character  char(32)  or other specified characters from the start of a string.

Example:

SELECT LTRIM('     Five spaces are at the beginning of this string.');

Example:

DECLARE @string_to_trim VARCHAR(60);
SET @string_to_trim = '     Five spaces are at the beginning of this string.';
SELECT
    @string_to_trim AS 'Original string',
    LTRIM(@string_to_trim) AS 'Without spaces';
GO

Example:

SELECT LTRIM('123abc.' , '123.');

colLength #

Arguments

:: SExp 
-> SExp

column

-> SExp 

Origin documentation for colLength

Syntax:

COL_LENGTH ( 'table' , 'column' )

This function returns the defined length of a column, in bytes.

Example:

USE AdventureWorks2012;
GO
CREATE TABLE t1(c1 VARCHAR(40), c2 NVARCHAR(40) );
GO
SELECT COL_LENGTH('t1','c1')AS 'VarChar',
      COL_LENGTH('t1','c2')AS 'NVarChar';
GO
DROP TABLE t1;

greatest #

Arguments

:: NonEmpty SExp

expression1

-> SExp 

Origin documentation for greatest

Syntax:

GREATEST ( expression1 [ ,...expressionN ] )

This function returns the maximum value from a list of one or more expressions.

Example:

SELECT GREATEST ( '6.62', 3.1415, N'7' ) AS GreatestVal;
GO

Example:

SELECT GREATEST ('Glacier', N'Joshua Tree', 'Mount Rainier') AS GreatestString;
GO

Example:

SELECT P.Name, P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate AS ModelModifiedDate
    , GREATEST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) AS LatestDate
FROM SalesLT.Product AS P
INNER JOIN SalesLT.ProductModel AS PM on P.ProductModelID = PM.ProductModelID
WHERE GREATEST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) >='2007-01-01'
AND P.SellStartDate >='2007-01-01'
AND P.Name LIKE 'Touring %'
ORDER BY P.Name;

Example:

CREATE TABLE dbo.studies (
    VarX varchar(10) NOT NULL,
    Correlation decimal(4, 3) NULL
);

INSERT INTO dbo.studies VALUES ('Var1', 0.2), ('Var2', 0.825), ('Var3', 0.61);
GO

DECLARE @PredictionA DECIMAL(2,1) = 0.7;
DECLARE @PredictionB DECIMAL(3,1) = 0.65;

SELECT VarX, Correlation
FROM dbo.studies
WHERE Correlation > GREATEST(@PredictionA, @PredictionB);
GO

Example:

CREATE TABLE dbo.studies (
    VarX varchar(10) NOT NULL,
    Correlation decimal(4, 3) NULL
);

INSERT INTO dbo.studies VALUES ('Var1', 0.2), ('Var2', 0.825), ('Var3', 0.61);
GO

DECLARE @VarX decimal(4, 3) = 0.59;

SELECT VarX, Correlation, GREATEST(Correlation, 0, @VarX) AS GreatestVar
FROM dbo.studies;
GO

filePropertyex #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for filePropertyex

Syntax:

FILEPROPERTYEX ( name , property )

Returns the specified extended file 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 or for extended file properties that do not exist. Currently, extended file properties only apply to databases that are in Azure Blob storage.

Example:

SELECT s.file_id,
       s.type_desc,
       s.name,
       FILEPROPERTYEX(s.name, 'BlobTier') AS BlobTier,
       FILEPROPERTYEX(s.name, 'AccountType') AS AccountType,
       FILEPROPERTYEX(s.name, 'IsInferredTier') AS IsInferredTier,
       FILEPROPERTYEX(s.name, 'IsPageBlob') AS IsPageBlob
FROM sys.database_files AS s
WHERE s.type_desc IN ('ROWS', 'LOG');

fileGroupProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for fileGroupProperty

Syntax:

FILEGROUPPROPERTY ( filegroup_name, property )

This function returns the filegroup property value for a specified name and filegroup value.

Example:

SELECT FILEGROUPPROPERTY('PRIMARY', 'IsDefault') AS 'Default Filegroup';
GO

objectIdFromEdgeId #

Arguments

:: SExp

edgeId

-> SExp 

Origin documentation for objectIdFromEdgeId

Syntax:

OBJECT_ID_FROM_EDGE_ID ( edge_id )

Returns the object ID for a given graph edge ID.

Example:

SELECT OBJECT_ID_FROM_EDGE_ID($from_id)
FROM likes;

varp #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for varp

Syntax:

-- Aggregate Function Syntax
VARP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VARP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance for the population for all values in the specified expression.

Example:

SELECT VARP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VARP(DISTINCT SalesAmountQuota)AS Distinct_Values, VARP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VARP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

hashBytes_SHA2_512 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_SHA2_512

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_SHA2_256 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_SHA2_256

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_SHA1 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_SHA1

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_SHA #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_SHA

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_MD5 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_MD5

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_MD4 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_MD4

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

hashBytes_MD2 #

Arguments

:: SExp

input

-> SExp 

Origin documentation for hashBytes_MD2

Syntax:

HASHBYTES ( '<algorithm>', { @input | 'input' } )

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512

Returns the MD2, MD4, MD5, SHA, SHA1, or SHA2 hash of its input in SQL Server.

Example:

DECLARE @HashThis NVARCHAR(32);
SET @HashThis = CONVERT(NVARCHAR(32),'dslfdkjLK85kldhnv$n000#knf');
SELECT HASHBYTES('SHA2_256', @HashThis);

Example:

CREATE TABLE dbo.Test1 (c1 NVARCHAR(32));
INSERT dbo.Test1 VALUES ('This is a test.');
INSERT dbo.Test1 VALUES ('This is test 2.');
SELECT HASHBYTES('SHA2_256', c1) FROM dbo.Test1;

identCurrent #

Arguments

:: SExp

tableOrView

-> SExp 

Origin documentation for identCurrent

Syntax:

IDENT_CURRENT( 'table_or_view' )

Returns the last identity value generated for a specified table or view. The last identity value generated can be for any session and any scope.

Example:

USE AdventureWorks2012;
GO
SELECT IDENT_CURRENT ('Person.Address') AS Current_Identity;
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID(N't6', N'U') IS NOT NULL
    DROP TABLE t6;
GO
IF OBJECT_ID(N't7', N'U') IS NOT NULL
    DROP TABLE t7;
GO
CREATE TABLE t6(id INT IDENTITY);
CREATE TABLE t7(id INT IDENTITY(100,1));
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
   INSERT t7 DEFAULT VALUES
END;
GO
--End of trigger definition

SELECT id FROM t6;
--IDs empty.

SELECT id FROM t7;
--ID is empty.

--Do the following in Session 1
INSERT t6 DEFAULT VALUES;
SELECT @@IDENTITY;
/*Returns the value 100. This was inserted by the trigger.*/

SELECT SCOPE_IDENTITY();
/* Returns the value 1. This was inserted by the
INSERT statement two statements before this query.*/

SELECT IDENT_CURRENT('t7');
/* Returns value inserted into t7, that is in the trigger.*/

SELECT IDENT_CURRENT('t6');
/* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/

-- Do the following in Session 2.
SELECT @@IDENTITY;
/* Returns NULL because there has been no INSERT action
up to this point in this session.*/

SELECT SCOPE_IDENTITY();
/* Returns NULL because there has been no INSERT action
up to this point in this scope in this session.*/

SELECT IDENT_CURRENT('t7');
/* Returns the last value inserted into t7.*/

right #

Arguments

:: SExp 
-> SExp

integerExpression

-> SExp 

Origin documentation for right

Syntax:

RIGHT ( character_expression , integer_expression )

Returns the right part of a character string with the specified number of characters.

Example:

SELECT RIGHT(FirstName, 5) AS 'First Name'
FROM Person.Person
WHERE BusinessEntityID < 5
ORDER BY FirstName;
GO

Example:

-- Uses AdventureWorks

SELECT RIGHT(LastName, 5) AS Name
FROM dbo.DimEmployee
ORDER BY EmployeeKey;

Example:

SELECT RIGHT('abcdefg', 2);

power #

Arguments

:: SExp 
-> SExp

y

-> SExp 

Origin documentation for power

Syntax:

POWER ( float_expression , y )

Returns the value of the specified expression to the specified power.

Example:

DECLARE @input1 FLOAT;
DECLARE @input2 FLOAT;
SET @input1= 2;
SET @input2 = 2.5;
SELECT POWER(@input1, 3) AS Result1, POWER(@input2, 3) AS Result2;

Example:

SELECT
POWER(CAST(2.0 AS FLOAT), -100.0) AS FloatResult,
POWER(2, -100.0) AS IntegerResult,
POWER(CAST(2.0 AS INT), -100.0) AS IntegerResult,
POWER(2.0, -100.0) AS Decimal1Result,
POWER(2.00, -100.0) AS Decimal2Result,
POWER(CAST(2.0 AS DECIMAL(5,2)), -100.0) AS Decimal2Result;
GO

Example:

DECLARE @value INT, @counter INT;
SET @value = 2;
SET @counter = 1;

WHILE @counter < 5
   BEGIN
      SELECT POWER(@value, @counter)
      SET NOCOUNT ON
      SET @counter = @counter + 1
      SET NOCOUNT OFF
   END;
GO

Example:

SELECT POWER(2.0, 3);

contextInfo :: SExp #

Origin documentation for contextInfo

Syntax:

CONTEXT_INFO()

This function returns the context_info value either set for the current session or batch, or derived through use of the SET CONTEXT_INFO statement.

Example:

SET CONTEXT_INFO 0x1256698456;
GO
SELECT CONTEXT_INFO();
GO

reverse #

Arguments

:: SExp

stringExpression

-> SExp 

Origin documentation for reverse

Syntax:

REVERSE ( string_expression )

Returns the reverse order of a string value.

Example:

SELECT FirstName, REVERSE(FirstName) AS Reverse
FROM Person.Person
WHERE BusinessEntityID < 5
ORDER BY FirstName;
GO

Example:

DECLARE @myvar VARCHAR(10);
SET @myvar = 'sdrawkcaB';
SELECT REVERSE(@myvar) AS Reversed ;
GO

Example:

SELECT REVERSE(1234) AS Reversed ;
GO

Example:

SELECT name, REVERSE(name) FROM sys.databases;
GO

sessionUser :: SExp #

Origin documentation for sessionUser

Syntax:

SESSION_USER

SESSION_USER returns the user name of the current context in the current database.

Example:

DECLARE @session_usr NCHAR(30);
SET @session_usr = SESSION_USER;
SELECT 'This session''s current user is: '+ @session_usr;
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE deliveries3
(
 order_id INT IDENTITY(5000, 1) NOT NULL,
 cust_id  INT NOT NULL,
 order_date SMALLDATETIME NOT NULL DEFAULT GETDATE(),
 delivery_date SMALLDATETIME NOT NULL DEFAULT
    DATEADD(dd, 10, GETDATE()),
 received_shipment NCHAR(30) NOT NULL DEFAULT SESSION_USER
);
GO

Example:

EXECUTE AS USER = 'Wanida'
INSERT deliveries3 (cust_id)
VALUES (7510);
INSERT deliveries3 (cust_id)
VALUES (7231);
REVERT;
EXECUTE AS USER = 'Sylvester'
INSERT deliveries3 (cust_id)
VALUES (7028);
REVERT;
EXECUTE AS USER = 'Alejandro'
INSERT deliveries3 (cust_id)
VALUES (7392);
INSERT deliveries3 (cust_id)
VALUES (7452);
REVERT;
GO

Example:

SELECT order_id AS 'Order #', cust_id AS 'Customer #',
   delivery_date AS 'When Delivered', received_shipment
   AS 'Received By'
FROM deliveries3
ORDER BY order_id;
GO

Example:

SELECT SESSION_USER;

__packReceived :: SExp #

Origin documentation for __packReceived

Syntax:

@@PACK_RECEIVED

Returns the number of input packets read from the network by SQL Server since it was last started.

Example:

SELECT @@PACK_RECEIVED AS 'Packets Received';

sqrt #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for sqrt

Syntax:

SQRT ( float_expression )

Returns the square root of the specified float value.

Example:

DECLARE @myvalue FLOAT;
SET @myvalue = 1.00;
WHILE @myvalue < 10.00
   BEGIN
      SELECT SQRT(@myvalue);
      SET @myvalue = @myvalue + 1
   END;
GO

Example:

SELECT SQRT(1.00), SQRT(10.00);

sysDateTimeOffset :: SExp #

Origin documentation for sysDateTimeOffset

Syntax:

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.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

SELECT SYSDATETIME() AS [SYSDATETIME()]
    ,SYSDATETIMEOFFSET() AS [SYSDATETIMEOFFSET()]
    ,SYSUTCDATETIME() AS [SYSUTCDATETIME()]
    ,CURRENT_TIMESTAMP AS [CURRENT_TIMESTAMP]
    ,GETDATE() AS [GETDATE()]
    ,GETUTCDATE() AS [GETUTCDATE()];

Example:

SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, SYSDATETIMEOFFSET())
    ,CONVERT (date, SYSUTCDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE())
    ,CONVERT (date, GETUTCDATE());

Example:

SELECT CONVERT (time, SYSDATETIME()) AS [SYSDATETIME()]
    ,CONVERT (time, SYSDATETIMEOFFSET()) AS [SYSDATETIMEOFFSET()]
    ,CONVERT (time, SYSUTCDATETIME()) AS [SYSUTCDATETIME()]
    ,CONVERT (time, CURRENT_TIMESTAMP) AS [CURRENT_TIMESTAMP]
    ,CONVERT (time, GETDATE()) AS [GETDATE()]
    ,CONVERT (time, GETUTCDATE()) AS [GETUTCDATE()];

cursorStatus_VARIABLE #

Arguments

:: SExp

cursorVariable

-> SExp 

Origin documentation for cursorStatus_VARIABLE

Syntax:

CURSOR_STATUS
     (
          { 'local' , 'cursor_name' }
          | { 'global' , 'cursor_name' }
          | { 'variable' , 'cursor_variable' }
     )

For a given parameter, CURSOR_STATUS shows whether or not a cursor declaration has returned a cursor and result set.

Example:

CREATE TABLE #TMP
(
   ii INT
)
GO

INSERT INTO #TMP(ii) VALUES(1)
INSERT INTO #TMP(ii) VALUES(2)
INSERT INTO #TMP(ii) VALUES(3)

GO

--Create a cursor.
DECLARE cur CURSOR
FOR SELECT * FROM #TMP

--Display the status of the cursor before and after opening
--closing the cursor.

SELECT CURSOR_STATUS('global','cur') AS 'After declare'
OPEN cur
SELECT CURSOR_STATUS('global','cur') AS 'After Open'
CLOSE cur
SELECT CURSOR_STATUS('global','cur') AS 'After Close'

--Remove the cursor.
DEALLOCATE cur

--Drop the table.
DROP TABLE #TMP

cursorStatus_GLOBAL #

Arguments

:: SExp

cursorName

-> SExp 

Origin documentation for cursorStatus_GLOBAL

Syntax:

CURSOR_STATUS
     (
          { 'local' , 'cursor_name' }
          | { 'global' , 'cursor_name' }
          | { 'variable' , 'cursor_variable' }
     )

For a given parameter, CURSOR_STATUS shows whether or not a cursor declaration has returned a cursor and result set.

Example:

CREATE TABLE #TMP
(
   ii INT
)
GO

INSERT INTO #TMP(ii) VALUES(1)
INSERT INTO #TMP(ii) VALUES(2)
INSERT INTO #TMP(ii) VALUES(3)

GO

--Create a cursor.
DECLARE cur CURSOR
FOR SELECT * FROM #TMP

--Display the status of the cursor before and after opening
--closing the cursor.

SELECT CURSOR_STATUS('global','cur') AS 'After declare'
OPEN cur
SELECT CURSOR_STATUS('global','cur') AS 'After Open'
CLOSE cur
SELECT CURSOR_STATUS('global','cur') AS 'After Close'

--Remove the cursor.
DEALLOCATE cur

--Drop the table.
DROP TABLE #TMP

cursorStatus_LOCAL #

Arguments

:: SExp

cursorName

-> SExp 

Origin documentation for cursorStatus_LOCAL

Syntax:

CURSOR_STATUS
     (
          { 'local' , 'cursor_name' }
          | { 'global' , 'cursor_name' }
          | { 'variable' , 'cursor_variable' }
     )

For a given parameter, CURSOR_STATUS shows whether or not a cursor declaration has returned a cursor and result set.

Example:

CREATE TABLE #TMP
(
   ii INT
)
GO

INSERT INTO #TMP(ii) VALUES(1)
INSERT INTO #TMP(ii) VALUES(2)
INSERT INTO #TMP(ii) VALUES(3)

GO

--Create a cursor.
DECLARE cur CURSOR
FOR SELECT * FROM #TMP

--Display the status of the cursor before and after opening
--closing the cursor.

SELECT CURSOR_STATUS('global','cur') AS 'After declare'
OPEN cur
SELECT CURSOR_STATUS('global','cur') AS 'After Open'
CLOSE cur
SELECT CURSOR_STATUS('global','cur') AS 'After Close'

--Remove the cursor.
DEALLOCATE cur

--Drop the table.
DROP TABLE #TMP

columnProperty #

Arguments

:: SExp 
-> SExp 
-> SExp

property

-> SExp 

Origin documentation for columnProperty

Syntax:

COLUMNPROPERTY ( id , column , property )

This function returns column or parameter information.

Example:

USE AdventureWorks2012;
GO
SELECT COLUMNPROPERTY( OBJECT_ID('Person.Person'),'LastName','PRECISION')AS 'Column Length';
GO

__packSent :: SExp #

Origin documentation for __packSent

Syntax:

@@PACK_SENT

Returns the number of output packets written to the network by SQL Server since it was last started.

Example:

SELECT @@PACK_SENT AS 'Pack Sent';

fileGroupName #

Arguments

:: SExp

filegroupId'

-> SExp 

Origin documentation for fileGroupName

Syntax:

FILEGROUP_NAME ( filegroup_id )

This function returns the filegroup name for the specified filegroup identification (ID) number.

Example:

SELECT FILEGROUP_NAME(1) AS [Filegroup Name];
GO

errorProcedure :: SExp #

Origin documentation for errorProcedure

Syntax:

ERROR_PROCEDURE ( )

This function returns the name of the stored procedure or trigger where an error occurs, if that error caused the CATCH block of a TRY...CATCH construct to execute.

Example:

-- Verify that the stored procedure does not already exist.
IF OBJECT_ID ( 'usp_ExampleProc', 'P' ) IS NOT NULL
    DROP PROCEDURE usp_ExampleProc;
GO

-- Create a stored procedure that
-- generates a divide-by-zero error.
CREATE PROCEDURE usp_ExampleProc
AS
    SELECT 1/0;
GO

BEGIN TRY
    -- Execute the stored procedure inside the TRY block.
    EXECUTE usp_ExampleProc;
END TRY
BEGIN CATCH
    SELECT ERROR_PROCEDURE() AS ErrorProcedure;
END CATCH;
GO

Example:

-- Verify that the stored procedure does not already exist.
IF OBJECT_ID ( 'usp_ExampleProc', 'P' ) IS NOT NULL
    DROP PROCEDURE usp_ExampleProc;
GO

-- Create a stored procedure that
-- generates a divide-by-zero error.
CREATE PROCEDURE usp_ExampleProc
AS
    SELECT 1/0;
GO

BEGIN TRY
    -- Execute the stored procedure inside the TRY block.
    EXECUTE usp_ExampleProc;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_MESSAGE() AS ErrorMessage,
        ERROR_LINE() AS ErrorLine;
        END CATCH;
GO

publishingserverName :: SExp #

Origin documentation for publishingserverName

Syntax:

PUBLISHINGSERVERNAME()

Returns the name of the originating Publisher for a published database participating in a database mirroring session. This function is executed at a Publisher instance of SQL Server on the publication database. Use it to determine the original Publisher of the published database.

stringAgg_WITHIN_GROUP_ORDER_BY #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> Maybe OrderDir

maybeOrderdir

-> SExp 

Origin documentation for stringAgg_WITHIN_GROUP_ORDER_BY

Syntax:

STRING_AGG ( expression, separator ) [ <order_clause> ]

<order_clause> ::=
    WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )

Concatenates the values of string expressions and places separator values between them. The separator isn't added at the end of string.

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG (CONVERT(NVARCHAR(max),FirstName), CHAR(13)) AS csv
FROM Person.Person;
GO

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(FirstName,'N/A')), ',') AS csv
FROM Person.Person;
GO

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG(CONVERT(NVARCHAR(max), CONCAT(FirstName, ' ', LastName, '(', ModifiedDate, ')')), CHAR(13)) AS names
FROM Person.Person;
GO

Example:

SELECT a.articleId, title, STRING_AGG (tag, ',') as tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
    ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
GO

Example:

USE AdventureWorks2019
GO

SELECT TOP 10 City, STRING_AGG(CONVERT(NVARCHAR(max), EmailAddress), ';') AS emails
FROM Person.BusinessEntityAddress AS BEA
INNER JOIN Person.Address AS A ON BEA.AddressID = A.AddressID
INNER JOIN Person.EmailAddress AS EA ON BEA.BusinessEntityID = EA.BusinessEntityID
GROUP BY City;
GO

Example:

USE AdventureWorks2019
GO

SELECT TOP 10 City, STRING_AGG(CONVERT(NVARCHAR(max), EmailAddress), ';') WITHIN GROUP (ORDER BY EmailAddress ASC) AS Emails
FROM Person.BusinessEntityAddress AS BEA
INNER JOIN Person.Address AS A ON BEA.AddressID = A.AddressID
INNER JOIN Person.EmailAddress AS EA ON BEA.BusinessEntityID = EA.BusinessEntityID
GROUP BY City;
GO

stringAgg #

Arguments

:: SExp 
-> SExp

separator

-> SExp 

Origin documentation for stringAgg

Syntax:

STRING_AGG ( expression, separator ) [ <order_clause> ]

<order_clause> ::=
    WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )

Concatenates the values of string expressions and places separator values between them. The separator isn't added at the end of string.

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG (CONVERT(NVARCHAR(max),FirstName), CHAR(13)) AS csv
FROM Person.Person;
GO

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(FirstName,'N/A')), ',') AS csv
FROM Person.Person;
GO

Example:

USE AdventureWorks2019
GO
SELECT STRING_AGG(CONVERT(NVARCHAR(max), CONCAT(FirstName, ' ', LastName, '(', ModifiedDate, ')')), CHAR(13)) AS names
FROM Person.Person;
GO

Example:

SELECT a.articleId, title, STRING_AGG (tag, ',') as tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
    ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
GO

Example:

USE AdventureWorks2019
GO

SELECT TOP 10 City, STRING_AGG(CONVERT(NVARCHAR(max), EmailAddress), ';') AS emails
FROM Person.BusinessEntityAddress AS BEA
INNER JOIN Person.Address AS A ON BEA.AddressID = A.AddressID
INNER JOIN Person.EmailAddress AS EA ON BEA.BusinessEntityID = EA.BusinessEntityID
GROUP BY City;
GO

Example:

USE AdventureWorks2019
GO

SELECT TOP 10 City, STRING_AGG(CONVERT(NVARCHAR(max), EmailAddress), ';') WITHIN GROUP (ORDER BY EmailAddress ASC) AS Emails
FROM Person.BusinessEntityAddress AS BEA
INNER JOIN Person.Address AS A ON BEA.AddressID = A.AddressID
INNER JOIN Person.EmailAddress AS EA ON BEA.BusinessEntityID = EA.BusinessEntityID
GROUP BY City;
GO

keyGuid #

Arguments

:: SExp

keyName

-> SExp 

Origin documentation for keyGuid

Syntax:

Key_GUID( 'Key_Name' )

Returns the GUID of a symmetric key in the database.

Example:

SELECT Key_GUID('ABerglundKey1');

appName :: SExp #

Origin documentation for appName

Syntax:

APP_NAME  ( )

This function returns the application name for the current session, if the application sets that name value.

Important

The client provides the application name, and APP_NAME does not verify the application name value in any way. Do not use APP_NAME as part of a security check.

Example:

USE AdventureWorks2012;
GO
IF APP_NAME() = 'Microsoft SQL Server Management Studio - Query'
PRINT 'This process was started by ' + APP_NAME() + '. The date is ' + CONVERT ( VARCHAR(100) , GETDATE(), 101) + '.';
ELSE
PRINT 'This process was started by ' + APP_NAME() + '. The date is ' + CONVERT ( VARCHAR(100) , GETDATE(), 102) + '.';
GO

certId #

Arguments

:: SExp

certName

-> SExp 

Origin documentation for certId

Syntax:

CERT_ID ( 'cert_name' )

This function returns the ID value of a certificate.

Example:

SELECT Cert_ID('ABerglundCert3');
GO

__Version :: SExp #

Origin documentation for __Version

Syntax:

@@VERSION

Returns system and build information for the current installation of SQL Server.

Note

We are aware of an issue where the product version reported by @@VERSION is incorrect for Azure SQL Database , Azure SQL Managed Instance and Azure Synapse Analytics .

The version of the SQL Server database engine run by Azure SQL Database, Azure SQL Managed Instance and Azure Synapse Analytics is always ahead of the on-premises version of SQL Server, and includes the latest security fixes. This means that the patch level is always on par with or ahead of the on-premises version of SQL Server, and that the latest features available in SQL Server are available in these services.

To programmatically determine the engine edition, use SELECT SERVERPROPERTY(EngineEdition). This query will return '5' for Azure SQL Database, '8' for Azure SQL Managed Instance, and '6' or '11' for Azure Synapse.

We will update the documentation once this issue is resolved.

Example:

SELECT @@VERSION AS 'SQL Server Version';

Example:

SELECT @@VERSION AS 'SQL Server PDW Version';

fileProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for fileProperty

Syntax:

FILEPROPERTY ( file_name , property )

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.

Example:

SELECT FILEPROPERTY('AdventureWorks2012_Data', 'IsPrimaryFile')AS [Primary File];
GO

errorSeverity :: SExp #

Origin documentation for errorSeverity

Syntax:

ERROR_SEVERITY ( )

This function returns the severity value of the error where an error occurs, if that error caused the CATCH block of a TRY...CATCH construct to execute.

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

scopeIdentity :: SExp #

Origin documentation for scopeIdentity

Syntax:

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.

Example:

USE tempdb;
GO
CREATE TABLE TZ (
   Z_id  INT IDENTITY(1,1)PRIMARY KEY,
   Z_name VARCHAR(20) NOT NULL);

INSERT TZ
   VALUES ('Lisa'),('Mike'),('Carla');

SELECT * FROM TZ;

Example:

CREATE TABLE TY (
   Y_id  INT IDENTITY(100,5)PRIMARY KEY,
   Y_name VARCHAR(20) NULL);

INSERT TY (Y_name)
   VALUES ('boathouse'), ('rocks'), ('elevator');

SELECT * FROM TY;

Example:

CREATE TRIGGER Ztrig
ON TZ
FOR INSERT AS
   BEGIN
   INSERT TY VALUES ('')
   END;

Example:

INSERT TZ VALUES ('Rosalie');

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
GO
SELECT @@IDENTITY AS [@@IDENTITY];
GO

Example:

USE AdventureWorks2012;
GO
INSERT INTO Person.ContactType ([Name]) VALUES ('Assistant to the Manager');
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
GO
SELECT @@IDENTITY AS [@@IDENTITY];
GO

Example:

INSERT INTO Sales.Customer ([TerritoryID],[PersonID]) VALUES (8,NULL);
GO
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];
GO
SELECT @@IDENTITY AS [@@IDENTITY];
GO

getFilestreamTransactionContext :: SExp #

Origin documentation for getFilestreamTransactionContext

Syntax:

GET_FILESTREAM_TRANSACTION_CONTEXT ()

Returns a token that represents the current transaction context of a session. The token is used by an application to bind FILESTREAM file-system streaming operations to the transaction. For a list of FILESTREAM topics, see Binary Large Object (Blob) Data (SQL Server) .

objectIdFromNodeId #

Arguments

:: SExp

nodeId

-> SExp 

Origin documentation for objectIdFromNodeId

Syntax:

OBJECT_ID_FROM_NODE_ID ( node_id )

Returns the object ID for a given graph node ID.

Example:

SELECT OBJECT_ID_FROM_NODE_ID($from_id)
FROM likes;

ascii #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for ascii

Syntax:

ASCII ( character_expression )

Returns the ASCII code value of the leftmost character of a character expression.

Example:

SELECT ASCII('A') AS A, ASCII('B') AS B,
ASCII('a') AS a, ASCII('b') AS b,
ASCII(1) AS [1], ASCII(2) AS [2];

Example:

SELECT ASCII('P') AS [ASCII], ASCII('æ') AS [Extended_ASCII];

Example:

SELECT NCHAR(80) AS [CHARACTER], NCHAR(195) AS [CHARACTER];

Example:

SELECT UNICODE('æ') AS [Extended_ASCII], NCHAR(230) AS [CHARACTER];

approxCountDistinct #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for approxCountDistinct

Syntax:

APPROX_COUNT_DISTINCT ( expression )

This function returns the approximate number of unique non-null values in a group.

Example:

SELECT APPROX_COUNT_DISTINCT(O_OrderKey) AS Approx_Distinct_OrderKey
FROM dbo.Orders;

Example:

SELECT O_OrderStatus, APPROX_COUNT_DISTINCT(O_OrderKey) AS Approx_Distinct_OrderKey
FROM dbo.Orders
GROUP BY O_OrderStatus
ORDER BY O_OrderStatus;

keyId #

Arguments

:: SExp

keyName

-> SExp 

Origin documentation for keyId

Syntax:

Key_ID ( 'Key_Name' )

Returns the ID of a symmetric key in the current database.

Example:

SELECT KEY_ID('ABerglundKey1');

Example:

SELECT KEY_ID('#ABerglundKey2');

__identity :: SExp #

Origin documentation for __identity

Syntax:

@@IDENTITY

Is a system function that returns the last-inserted identity value.

Example:

USE AdventureWorks2012;
GO
--Display the value of LocationID in the last row in the table.
SELECT MAX(LocationID) FROM Production.Location;
GO
INSERT INTO Production.Location (Name, CostRate, Availability, ModifiedDate)
VALUES ('Damaged Goods', 5, 2.5, GETDATE());
GO
SELECT @@IDENTITY AS 'Identity';
GO
--Display the value of LocationID of the newly inserted row.
SELECT MAX(LocationID) FROM Production.Location;
GO

__options :: SExp #

Origin documentation for __options

Syntax:

@@OPTIONS

Returns information about the current SET options.

Example:

SELECT @@OPTIONS AS OriginalOptionsValue;
SET CONCAT_NULL_YIELDS_NULL OFF;
SELECT 'abc' + NULL AS ResultWhen_OFF, @@OPTIONS AS OptionsValueWhen_OFF;

SET CONCAT_NULL_YIELDS_NULL ON;
SELECT 'abc' + NULL AS ResultWhen_ON, @@OPTIONS AS OptionsValueWhen_ON;

Example:

SET NOCOUNT ON
IF @@OPTIONS & 512 > 0
RAISERROR ('Current user has SET NOCOUNT turned on.', 1, 1)

Example:

SELECT S.Bits,
    FLAGS.*
FROM (
    SELECT optRef,
        posRef,
        flagCheck
    FROM (
        SELECT ones.n + tens.n * 10
        FROM ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9) ) ones(n),
            ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9) ) tens(n)
        ) f1(powRef)
    CROSS APPLY (
        SELECT POWER(2, powRef)
        WHERE powRef <= 16
        ) f2(binRef)
    CROSS JOIN (
        VALUES (@@OPTIONS)
        ) f3(optRef)
    CROSS APPLY (
        SELECT (optRef & binRef) / binRef
        ) f4(flagRef)
    CROSS APPLY (
        SELECT RIGHT(CONVERT(VARCHAR(2), CAST(powRef AS VARBINARY(1)), 2), 1) [posRef],
            CAST(flagRef AS INT) [flagCheck]
        ) pref
    ) TP
PIVOT( MAX( flagCheck ) FOR posRef IN ( [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [A], [B], [C], [D], [E], [F] )) P
CROSS APPLY (
    SELECT CONCAT ( '', [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [A], [B], [C], [D], [E], [F] ),
        CONCAT ( '', [F], [E], [D], [C], [B], [A], [9], [8], [7], [6], [5], [4], [3], [2], [1], [0] )
    ) S (stib, Bits)
CROSS APPLY (
    SELECT
          CAST(P.[0] AS BIT) /* 1     */ [DISABLE_DEF_CNST_CHK] -- Controls interim or deferred constraint checking.
        , CAST(P.[1] AS BIT) /* 2     */ [IMPLICIT_TRANSACTIONS] -- For dblib network library connections, controls whether a transaction is started implicitly when a statement is executed. The IMPLICIT_TRANSACTIONS setting has no effect on ODBC or OLEDB connections.
        , CAST(P.[2] AS BIT) /* 4     */ [CURSOR_CLOSE_ON_COMMIT] -- Controls behavior of cursors after a commit operation has been performed.
        , CAST(P.[3] AS BIT) /* 8     */ [ANSI_WARNINGS] -- Controls truncation and NULL in aggregate warnings.
        , CAST(P.[4] AS BIT) /* 16    */ [ANSI_PADDING] -- Controls padding of fixed-length variables.
        , CAST(P.[5] AS BIT) /* 32    */ [ANSI_NULLS] -- Controls NULL handling when using equality operators.
        , CAST(P.[6] AS BIT) /* 64    */ [ARITHABORT] -- Terminates a query when an overflow or divide-by-zero error occurs during query execution.
        , CAST(P.[7] AS BIT) /* 128   */ [ARITHIGNORE] -- Returns NULL when an overflow or divide-by-zero error occurs during a query.
        , CAST(P.[8] AS BIT) /* 256   */ [QUOTED_IDENTIFIER] -- Differentiates between single and double quotation marks when evaluating an expression.
        , CAST(P.[9] AS BIT) /* 512   */ [NOCOUNT] -- Turns off the message returned at the end of each statement that states how many rows were affected.
        , CAST(P.[A] AS BIT) /* 1024  */ [ANSI_NULL_DFLT_ON] -- Alters the session's behavior to use ANSI compatibility for nullability. New columns defined without explicit nullability are defined to allow nulls.
        , CAST(P.[B] AS BIT) /* 2048  */ [ANSI_NULL_DFLT_OFF] -- Alters the session's behavior not to use ANSI compatibility for nullability. New columns defined without explicit nullability do not allow nulls.
        , CAST(P.[C] AS BIT) /* 4096  */ [CONCAT_NULL_YIELDS_NULL] -- Returns NULL when concatenating a NULL value with a string.
        , CAST(P.[D] AS BIT) /* 8192  */ [NUMERIC_ROUNDABORT] -- Generates an error when a loss of precision occurs in an expression.
        , CAST(P.[E] AS BIT) /* 16384 */ [XACT_ABORT] -- Rolls back a transaction if a Transact-SQL statement raises a run-time error.*/
    ) AS Flags;

rightShift #

Arguments

:: SExp 
-> SExp

shiftAmount

-> SExp 

Origin documentation for rightShift

Syntax:

RIGHT_SHIFT ( expression_value, shift_amount )
expression_value >> shift_amount

RIGHT_SHIFT takes two parameters, and returns the first parameter bit-shifted right by the number of bits specified in the second parameter.

The RIGHT_SHIFT function is also accessible through the >> operator.

Example:

SELECT RIGHT_SHIFT(12345, 5);

soundex #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for soundex

Syntax:

SOUNDEX ( character_expression )

Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings.

Example:

-- Using SOUNDEX
SELECT SOUNDEX ('Smith'), SOUNDEX ('Smythe');

Example:

-- Using DIFFERENCE
SELECT DIFFERENCE('Smithers', 'Smythers');
GO

Example:

SELECT DIFFERENCE('Anothers', 'Brothers');
GO

datepart #

Arguments

:: SExp 
-> SExp

date

-> SExp 

Origin documentation for datepart

Syntax:

DATEPART ( datepart , date )

This function returns an integer representing the specified datepart of the specified date .

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SELECT DATEPART (tzoffset, '2007-05-10  00:00:01.1234567 +05:10');

Example:

SELECT DATEPART(year, '12:10:30.123')
    ,DATEPART(month, '12:10:30.123')
    ,DATEPART(day, '12:10:30.123')
    ,DATEPART(dayofyear, '12:10:30.123')
    ,DATEPART(weekday, '12:10:30.123');

Example:

DECLARE @t time = '12:10:30.123';
SELECT DATEPART(year, @t);

Example:

SELECT DATEPART(millisecond, '00:00:01.1234567'); -- Returns 123
SELECT DATEPART(microsecond, '00:00:01.1234567'); -- Returns 123456
SELECT DATEPART(nanosecond,  '00:00:01.1234567'); -- Returns 123456700

Example:

SELECT DATEPART(year, 0), DATEPART(month, 0), DATEPART(day, 0);

-- Returns: 1900    1    1

Example:

-- Uses AdventureWorks

SELECT TOP(1) DATEPART (day,'12/20/1974') FROM dbo.DimCustomer;

-- Returns: 20

Example:

-- Uses AdventureWorks

SELECT TOP(1) DATEPART (year,'12/20/1974') FROM dbo.DimCustomer;

-- Returns: 1974

rtrim #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for rtrim

Syntax:

RTRIM ( character_expression )

Returns a character string after truncating all trailing spaces.

Removes space character  char(32)  or other specified characters from the end of a string.

Example:

SELECT RTRIM('Removes trailing spaces.   ');

Example:

DECLARE @string_to_trim VARCHAR(60);
SET @string_to_trim = 'Four spaces are after the period in this sentence.    ';
SELECT @string_to_trim + ' Next string.';
SELECT RTRIM(@string_to_trim) + ' Next string.';
GO

Example:

SELECT RTRIM('.123abc.' , 'abc.');

__Datefirst :: SExp #

Origin documentation for __Datefirst

Syntax:

@@DATEFIRST

This function returns the current value of SET DATEFIRST , for a specific session.

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SET DATEFIRST 3;
GO
SELECT @@DATEFIRST; -- 3 (Wednesday)
GO

Example:

SET LANGUAGE Italian;
GO
SELECT @@DATEFIRST;
GO
SET LANGUAGE us_english;
GO
SELECT @@DATEFIRST;

Example:

SET DATEFIRST 5;
SELECT @@DATEFIRST AS 'First Day'
    ,DATEPART(dw, SYSDATETIME()) AS 'Today';

Example:

SELECT @@DATEFIRST;

__lockTimeout :: SExp #

Origin documentation for __lockTimeout

Syntax:

@@LOCK_TIMEOUT

Returns the current lock time-out setting in milliseconds for the current session.

Example:

SELECT @@LOCK_TIMEOUT AS [Lock Timeout];
GO

Example:

SET LOCK_TIMEOUT 1800;
SELECT @@LOCK_TIMEOUT AS [Lock Timeout];
GO

fulltextcatalogProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for fulltextcatalogProperty

Syntax:

FULLTEXTCATALOGPROPERTY ('catalog_name' ,'property')

Returns information about full-text catalog properties in SQL Server.

Example:

USE AdventureWorks2012;
GO
SELECT fulltextcatalogproperty('Cat_Desc', 'ItemCount');
GO

errorLine :: SExp #

Origin documentation for errorLine

Syntax:

ERROR_LINE ( )

This function returns the line number of occurrence of an error that caused the CATCH block of a TRY...CATCH construct to execute.

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_LINE() AS ErrorLine;
END CATCH;
GO

Example:

-- Verify that the stored procedure does not already exist.
IF OBJECT_ID ( 'usp_ExampleProc', 'P' ) IS NOT NULL
    DROP PROCEDURE usp_ExampleProc;
GO

-- Create a stored procedure that
-- generates a divide-by-zero error.
CREATE PROCEDURE usp_ExampleProc
AS
    SELECT 1/0;
GO

BEGIN TRY
    -- Execute the stored procedure inside the TRY block.
    EXECUTE usp_ExampleProc;
END TRY
BEGIN CATCH
    SELECT ERROR_LINE() AS ErrorLine;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

compress #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for compress

Syntax:

COMPRESS ( expression )

This function compresses the input expression, using the GZIP algorithm. The function returns a byte array of type varbinary(max) .

Example:

INSERT INTO player (name, surname, info )
VALUES (N'Ovidiu', N'Cracium',
        COMPRESS(N'{"sport":"Tennis","age": 28,"rank":1,"points":15258, turn":17}'));

INSERT INTO player (name, surname, info )
VALUES (N'Michael', N'Raheem', compress(@info));

Example:

DELETE FROM player
OUTPUT deleted.id, deleted.name, deleted.surname, deleted.datemodifier, COMPRESS(deleted.info)
INTO dbo.inactivePlayers
WHERE datemodified < @startOfYear;

__idle :: SExp #

Origin documentation for __idle

Syntax:

@@IDLE

Returns the time that SQL Server has been idle since it was last started. The result is in CPU time increments, or "ticks," and is cumulative for all CPUs, so it may exceed the actual elapsed time. Multiply by @@TIMETICKS to convert to microseconds.

Note

If the time returned in @CPU_BUSY, or IO_BUSY exceeds approximately 49 days of cumulative CPU time, you receive an arithmetic overflow warning. In that case, the value of CPU_BUSY, IO_BUSY and @IDLE variables are not accurate.

Example:

SELECT @@IDLE * CAST(@@TIMETICKS AS float) AS 'Idle microseconds',
   GETDATE() AS 'as of';

databasePropertyex #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for databasePropertyex

Syntax:

DATABASEPROPERTYEX ( database , property )

For a specified database in SQL Server, this function returns the current setting of the specified database option or property.

Example:

SELECT DATABASEPROPERTYEX('AdventureWorks2014', 'IsAutoShrink');

Example:

SELECT
    DATABASEPROPERTYEX('AdventureWorks2014', 'Collation') AS Collation,
    DATABASEPROPERTYEX('AdventureWorks2014', 'Edition') AS Edition,
    DATABASEPROPERTYEX('AdventureWorks2014', 'ServiceObjective') AS ServiceObjective,
    DATABASEPROPERTYEX('AdventureWorks2014', 'MaxSizeInBytes') AS MaxSizeInBytes

Example:

SELECT DATABASEPROPERTYEX(DB_NAME(), 'Updateability');

certProperty_STRING_SID #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_STRING_SID

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_SID #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_SID

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_SUBJECT #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_SUBJECT

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_CERT_SERIAL_NUMBER #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_CERT_SERIAL_NUMBER

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_ISSUER_NAME #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_ISSUER_NAME

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_START_DATE #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_START_DATE

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

certProperty_EXPIRY_DATE #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certProperty_EXPIRY_DATE

Syntax:

CertProperty ( Cert_ID , '<PropertyName>' )

<PropertyName> ::=
   Expiry_Date | Start_Date | Issuer_Name
   | Cert_Serial_Number | Subject | SID | String_SID

Returns the value of a specified certificate property.

Example:

-- First create a certificate.
CREATE CERTIFICATE Marketing19 WITH
    START_DATE = '04/04/2004' ,
    EXPIRY_DATE = '07/07/2040' ,
    SUBJECT = 'Marketing Print Division';
GO

-- Now use CertProperty to examine certificate
-- Marketing19's properties.
DECLARE @CertSubject sql_variant;
set @CertSubject = CertProperty( Cert_ID('Marketing19'), 'Subject');
PRINT CONVERT(nvarchar, @CertSubject);
GO

errorNumber :: SExp #

Origin documentation for errorNumber

Syntax:

ERROR_NUMBER ( )

This function returns the error number of the error that caused the CATCH block of a TRY...CATCH construct to execute.

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

concatWs #

Arguments

:: SExp 
-> SExp 
-> NonEmpty SExp

argument2

-> SExp 

Origin documentation for concatWs

Syntax:

CONCAT_WS ( separator, argument1, argument2 [, argumentN]... )

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 .)

Example:

SELECT CONCAT_WS( ' - ', database_id, recovery_model_desc, containment_desc) AS DatabaseInfo
FROM sys.databases;

Example:

SELECT CONCAT_WS(',','1 Microsoft Way', NULL, NULL, 'Redmond', 'WA', 98052) AS Address;

Example:

SELECT
STRING_AGG(CONCAT_WS( ',', database_id, recovery_model_desc, containment_desc), char(13)) AS DatabaseInfo
FROM sys.databases

Example:

SELECT
STRING_AGG(CONCAT_WS( ',', database_id, ISNULL(recovery_model_desc,''), ISNULL(containment_desc,'N/A')), char(13)) AS DatabaseInfo
FROM sys.databases;

currentTimeZone :: SExp #

Origin documentation for currentTimeZone

Syntax:

CURRENT_TIMEZONE ( )

This function returns the name of the time zone observed by a server or an instance. For SQL Managed Instance, return value is based on the time zone of the instance itself assigned during instance creation, not the time zone of the underlying operating system.

Note

For SQL Database, the time zone is always set to UTC and CURRENT_TIMEZONE returns the name of the UTC time zone.

Example:

SELECT CURRENT_TIMEZONE();
/* Returned:
(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna
*/

systemUser :: SExp #

Origin documentation for systemUser

Syntax:

SYSTEM_USER

Allows a system-supplied value for the current login to be inserted into a table when no default value is specified.

Example:

DECLARE @sys_usr CHAR(30);
SET @sys_usr = SYSTEM_USER;
SELECT 'The current system user is: '+ @sys_usr;
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE Sales.Sales_Tracking
(
    Territory_id INT IDENTITY(2000, 1) NOT NULL,
    Rep_id INT NOT NULL,
    Last_sale DATETIME NOT NULL DEFAULT GETDATE(),
    SRep_tracking_user VARCHAR(30) NOT NULL DEFAULT SYSTEM_USER
);
GO
INSERT Sales.Sales_Tracking (Rep_id)
VALUES (151);
INSERT Sales.Sales_Tracking (Rep_id, Last_sale)
VALUES (293, '19980515');
INSERT Sales.Sales_Tracking (Rep_id, Last_sale)
VALUES (27882, '19980620');
INSERT Sales.Sales_Tracking (Rep_id)
VALUES (21392);
INSERT Sales.Sales_Tracking (Rep_id, Last_sale)
VALUES (24283, '19981130');
GO

Example:

SELECT * FROM Sales_Tracking ORDER BY Rep_id;
GO

Example:

SELECT SYSTEM_USER;

__maxConnections :: SExp #

Origin documentation for __maxConnections

Syntax:

@@MAX_CONNECTIONS

Returns the maximum number of simultaneous user connections allowed on an instance of SQL Server. The number returned is not necessarily the number currently configured.

Example:

SELECT @@MAX_CONNECTIONS AS 'Max Connections';

timeFromParts #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

precision

-> SExp 

Origin documentation for timeFromParts

Syntax:

TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )

Returns a time value for the specified time and with the specified precision.

Example:

SELECT TIMEFROMPARTS ( 23, 59, 59, 0, 0 ) AS Result;

Example:

SELECT TIMEFROMPARTS ( 14, 23, 44, 5, 1 );
SELECT TIMEFROMPARTS ( 14, 23, 44, 50, 2 );
SELECT TIMEFROMPARTS ( 14, 23, 44, 500, 3 );
GO

dateTime2FromParts #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

precision

-> SExp 

Origin documentation for dateTime2FromParts

Syntax:

DATETIME2FROMPARTS ( year, month, day, hour, minute, seconds, fractions, precision )

This function returns a datetime2 value for the specified date and time arguments. The returned value has a precision specified by the precision argument.

Example:

SELECT DATETIME2FROMPARTS ( 2010, 12, 31, 23, 59, 59, 0, 0 ) AS Result;

Example:

SELECT DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 5, 1 );
SELECT DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 50, 2 );
SELECT DATETIME2FROMPARTS ( 2011, 8, 15, 14, 23, 44, 500, 3 );
GO

__Timeticks :: SExp #

Origin documentation for __Timeticks

Syntax:

@@TIMETICKS

Returns the number of microseconds per tick.

Example:

SELECT @@TIMETICKS AS 'Time Ticks';

choose #

Arguments

:: SExp 
-> SExp 
-> NonEmpty SExp

val2

-> SExp 

Origin documentation for choose

Syntax:

CHOOSE ( index, val_1, val_2 [, val_n ] )

Returns the item at the specified index from a list of values in SQL Server.

Example:

SELECT CHOOSE ( 3, 'Manager', 'Director', 'Developer', 'Tester' ) AS Result;

Example:

USE AdventureWorks2012;
GO
SELECT ProductCategoryID, CHOOSE (ProductCategoryID, 'A','B','C','D','E') AS Expression1
FROM Production.ProductCategory;

Example:

SELECT Name, ModifiedDate,
CHOOSE(MONTH(ModifiedDate),'Winter','Winter', 'Spring','Spring','Spring','Summer','Summer',
                          'Summer','Autumn','Autumn','Autumn','Winter') AS Quarter_Modified
FROM SalesLT.ProductModel AS PM
WHERE Name LIKE '%Frame%'
ORDER BY ModifiedDate;

dateTimeOffsetFromParts #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

precision

-> SExp 

Origin documentation for dateTimeOffsetFromParts

Syntax:

DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions, hour_offset, minute_offset, precision )

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.

Example:

SELECT DATETIMEOFFSETFROMPARTS ( 2010, 12, 31, 14, 23, 23, 0, 12, 0, 7 ) AS Result;

Example:

SELECT DATETIMEOFFSETFROMPARTS ( 2011, 8, 15, 14, 30, 00, 5, 12, 30, 1 );
SELECT DATETIMEOFFSETFROMPARTS ( 2011, 8, 15, 14, 30, 00, 50, 12, 30, 2 );
SELECT DATETIMEOFFSETFROMPARTS ( 2011, 8, 15, 14, 30, 00, 500, 12, 30, 3 );
GO

sqlVariantProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for sqlVariantProperty

Syntax:

SQL_VARIANT_PROPERTY ( expression , property )

Returns the base data type and other information about a sql_variant value.

Example:

CREATE   TABLE tableA(colA sql_variant, colB int)
INSERT INTO tableA values ( cast (46279.1 as decimal(8,2)), 1689)
SELECT   SQL_VARIANT_PROPERTY(colA,'BaseType') AS 'Base Type',
         SQL_VARIANT_PROPERTY(colA,'Precision') AS 'Precision',
         SQL_VARIANT_PROPERTY(colA,'Scale') AS 'Scale'
FROM      tableA
WHERE      colB = 1689

Example:

DECLARE @v1 sql_variant;
SET @v1 = 'ABC';
SELECT @v1;
SELECT SQL_VARIANT_PROPERTY(@v1, 'BaseType');
SELECT SQL_VARIANT_PROPERTY(@v1, 'MaxLength');

errorState :: SExp #

Origin documentation for errorState

Syntax:

ERROR_STATE ( )

Returns the state number of the error that caused the CATCH block of a TRY...CATCH construct to be run.

Example:

BEGIN TRY
    -- Generate a divide by zero error
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_STATE() AS ErrorState;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

serverProperty #

Arguments

:: SExp

propertyname

-> SExp 

Origin documentation for serverProperty

Syntax:

SERVERPROPERTY ( 'propertyname' )

Returns property information about the server instance.

Example:

EXEC sp_dropserver 'current_server_name';
GO
EXEC sp_addserver 'new_server_name', 'local';
GO

Example:

SELECT
 SERVERPROPERTY('MachineName') AS ComputerName,
 SERVERPROPERTY('ServerName') AS InstanceName,
 SERVERPROPERTY('Edition') AS Edition,
 SERVERPROPERTY('ProductVersion') AS ProductVersion,
 SERVERPROPERTY('ProductLevel') AS ProductLevel;
GO

bitCount #

Arguments

:: SExp

expressionValue

-> SExp 

Origin documentation for bitCount

Syntax:

BIT_COUNT ( expression_value )

BIT_COUNT takes one parameter and returns the number of bits set to 1 in that parameter as a bigint type.

Example:

SELECT BIT_COUNT ( 0xabcdef ) as Count;

Example:

SELECT BIT_COUNT ( 17 ) as Count;

asymKeyId #

Arguments

:: SExp

asymKeyName

-> SExp 

Origin documentation for asymKeyId

Syntax:

ASYMKEY_ID ( 'Asym_Key_Name' )

Returns the ID of an asymmetric key.

Example:

SELECT ASYMKEY_ID('ABerglundKey11');
GO

nodeIdFromParts #

Arguments

:: SExp 
-> SExp

graphId

-> SExp 

Origin documentation for nodeIdFromParts

Syntax:

NODE_ID_FROM_PARTS ( object_id, graph_id )

Returns the character representation (JSON) of the node ID for a given object ID and graph ID.

Example:

INSERT INTO Person($node_id, ID, [name])
SELECT NODE_ID_FROM_PARTS(OBJECT_ID('Person'), ID) as node_id, ID, [name]
FROM OPENROWSET (BULK 'person_0_0.csv',
    DATA_SOURCE = 'staging_data_source',
    FORMATFILE = 'format-files/person.xml',
    FORMATFILE_DATA_SOURCE = 'format_files_source',
    FIRSTROW = 2) AS staging_data;
;

year #

Arguments

:: SExp

date

-> SExp 

Origin documentation for year

Syntax:

YEAR ( date )

Returns an integer that represents the year of the specified date .

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

SELECT YEAR('2010-04-30T01:01:01.1234567-07:00');

Example:

SELECT YEAR(0), MONTH(0), DAY(0);

Example:

SELECT TOP 1 YEAR(0), MONTH(0), DAY(0);

dateFromParts #

Arguments

:: SExp 
-> SExp 
-> SExp

day'

-> SExp 

Origin documentation for dateFromParts

Syntax:

DATEFROMPARTS ( year, month, day )

This function returns a date value that maps to the specified year, month, and day values.

Example:

SELECT DATEFROMPARTS ( 2010, 12, 31 ) AS Result;

parse_USING #

Arguments

:: SExp 
-> SExp 
-> SExp

culture

-> SExp 

Origin documentation for parse_USING

Syntax:

PARSE ( string_value AS data_type [ USING culture ] )

Returns the result of an expression, translated to the requested data type in SQL Server.

Example:

SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS Result;

Example:

SELECT PARSE('€345,98' AS money USING 'de-DE') AS Result;

Example:

-- The English language is mapped to en-US specific culture
SET LANGUAGE 'English';
SELECT PARSE('12/16/2010' AS datetime2) AS Result;

parse #

Arguments

:: SExp 
-> SExp

dataType

-> SExp 

Origin documentation for parse

Syntax:

PARSE ( string_value AS data_type [ USING culture ] )

Returns the result of an expression, translated to the requested data type in SQL Server.

Example:

SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS Result;

Example:

SELECT PARSE('€345,98' AS money USING 'de-DE') AS Result;

Example:

-- The English language is mapped to en-US specific culture
SET LANGUAGE 'English';
SELECT PARSE('12/16/2010' AS datetime2) AS Result;

pwdEncrypt #

Arguments

:: SExp

password

-> SExp 

Origin documentation for pwdEncrypt

Syntax:

PWDENCRYPT ( 'password' )

Returns the SQL Server password hash of the input value that uses the current version of the password hashing algorithm.

PWDENCRYPT is an older function and might not be supported in a future release of SQL Server. Use HASHBYTES instead. HASHBYTES provides more hashing algorithms.

verifySignedByAsymKey #

Arguments

:: SExp 
-> SExp 
-> SExp

signature

-> SExp 

Origin documentation for verifySignedByAsymKey

Syntax:

VerifySignedByAsymKey( Asym_Key_ID , clear_text , signature )

Tests whether digitally signed data has been changed since it was signed.

Example:

SELECT Data,
     VerifySignedByAsymKey( AsymKey_Id( 'WillisKey74' ), SignedData,
     DataSignature ) as IsSignatureValid
FROM [AdventureWorks2012].[SignedData04]
WHERE Description = N'data encrypted by asymmetric key ''WillisKey74''';
GO
RETURN;

Example:

SELECT Data
FROM [AdventureWorks2012].[SignedData04]
WHERE VerifySignedByAsymKey( AsymKey_Id( 'WillisKey74' ), Data,
     DataSignature ) = 1
AND Description = N'data encrypted by asymmetric key ''WillisKey74''';
GO

rowCountBig :: SExp #

Origin documentation for rowCountBig

Syntax:

ROWCOUNT_BIG ( )

Returns the number of rows affected by the last statement executed. This function operates like @@ROWCOUNT , except the return type of ROWCOUNT_BIG is bigint .

__fetchStatus :: SExp #

Origin documentation for __fetchStatus

Syntax:

@@FETCH_STATUS

This function returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

Example:

DECLARE Employee_Cursor CURSOR FOR
SELECT BusinessEntityID, JobTitle
FROM AdventureWorks2012.HumanResources.Employee;
OPEN Employee_Cursor;
FETCH NEXT FROM Employee_Cursor;
WHILE @@FETCH_STATUS = 0
   BEGIN
      FETCH NEXT FROM Employee_Cursor;
   END;
CLOSE Employee_Cursor;
DEALLOCATE Employee_Cursor;
GO

groupingId #

Arguments

:: NonEmpty SExp

columnExpression

-> SExp 

Origin documentation for groupingId

Syntax:

GROUPING_ID ( <column_expression>[ ,...n ] )

Is a function that computes the level of grouping. GROUPING_ID can be used only in the SELECT select list, HAVING, or ORDER BY clauses when GROUP BY is specified.

Example:

SELECT GROUPING_ID(A,B)
FROM T
GROUP BY CUBE(A,B)

Example:

SELECT 3 FROM T GROUP BY ()
UNION ALL
SELECT 1 FROM T GROUP BY A
UNION ALL
SELECT 2 FROM T GROUP BY B
UNION ALL
SELECT 0 FROM T GROUP BY A,B

Example:

SELECT D.Name
    ,CASE
    WHEN GROUPING_ID(D.Name, E.JobTitle) = 0 THEN E.JobTitle
    WHEN GROUPING_ID(D.Name, E.JobTitle) = 1 THEN N'Total: ' + D.Name
    WHEN GROUPING_ID(D.Name, E.JobTitle) = 3 THEN N'Company Total:'
        ELSE N'Unknown'
    END AS N'Job Title'
    ,COUNT(E.BusinessEntityID) AS N'Employee Count'
FROM HumanResources.Employee E
    INNER JOIN HumanResources.EmployeeDepartmentHistory DH
        ON E.BusinessEntityID = DH.BusinessEntityID
    INNER JOIN HumanResources.Department D
        ON D.DepartmentID = DH.DepartmentID
WHERE DH.EndDate IS NULL
    AND D.DepartmentID IN (12,14)
GROUP BY ROLLUP(D.Name, E.JobTitle);

Example:

SELECT D.Name
    ,E.JobTitle
    ,GROUPING_ID(D.Name, E.JobTitle) AS 'Grouping Level'
    ,COUNT(E.BusinessEntityID) AS N'Employee Count'
FROM HumanResources.Employee AS E
    INNER JOIN HumanResources.EmployeeDepartmentHistory AS DH
        ON E.BusinessEntityID = DH.BusinessEntityID
    INNER JOIN HumanResources.Department AS D
        ON D.DepartmentID = DH.DepartmentID
WHERE DH.EndDate IS NULL
    AND D.DepartmentID IN (12,14)
GROUP BY ROLLUP(D.Name, E.JobTitle)
--HAVING GROUPING_ID(D.Name, E.JobTitle) = 0; --All titles
--HAVING GROUPING_ID(D.Name, E.JobTitle) = 1; --Group by Name;

Example:

DECLARE @Grouping NVARCHAR(50);
DECLARE @GroupingLevel SMALLINT;
SET @Grouping = N'CountryRegionCode Total';

SELECT @GroupingLevel = (
    CASE @Grouping
        WHEN N'Grand Total'             THEN 15
        WHEN N'SalesPerson Total'       THEN 14
        WHEN N'Store Total'             THEN 13
        WHEN N'Store SalesPerson Total' THEN 12
        WHEN N'CountryRegionCode Total' THEN 11
        WHEN N'Group Total'             THEN 7
        ELSE N'Unknown'
    END);

SELECT
    T.[Group]
    ,T.CountryRegionCode
    ,S.Name AS N'Store'
    ,(SELECT P.FirstName + ' ' + P.LastName
        FROM Person.Person AS P
        WHERE P.BusinessEntityID = H.SalesPersonID)
        AS N'Sales Person'
    ,SUM(TotalDue)AS N'TotalSold'
    ,CAST(GROUPING(T.[Group])AS char(1)) +
        CAST(GROUPING(T.CountryRegionCode)AS char(1)) +
        CAST(GROUPING(S.Name)AS char(1)) +
        CAST(GROUPING(H.SalesPersonID)AS char(1))
        AS N'GROUPING base-2'
    ,GROUPING_ID((T.[Group])
        ,(T.CountryRegionCode),(S.Name),(H.SalesPersonID)
        ) AS N'GROUPING_ID'
    ,CASE
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) = 15 THEN N'Grand Total'
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) = 14 THEN N'SalesPerson Total'
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) = 13 THEN N'Store Total'
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) = 12 THEN N'Store SalesPerson Total'
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) = 11 THEN N'CountryRegionCode Total'
        WHEN GROUPING_ID(
            (T.[Group]),(T.CountryRegionCode)
            ,(S.Name),(H.SalesPersonID)
            ) =  7 THEN N'Group Total'
        ELSE N'Error'
        END AS N'Level'
FROM Sales.Customer AS C
    INNER JOIN Sales.Store AS S
        ON C.StoreID  = S.BusinessEntityID
    INNER JOIN Sales.SalesTerritory AS T
        ON C.TerritoryID  = T.TerritoryID
    INNER JOIN Sales.SalesOrderHeader AS H
        ON C.CustomerID = H.CustomerID
GROUP BY GROUPING SETS ((S.Name,H.SalesPersonID)
    ,(H.SalesPersonID),(S.Name)
    ,(T.[Group]),(T.CountryRegionCode),()
    )
HAVING GROUPING_ID(
    (T.[Group]),(T.CountryRegionCode),(S.Name),(H.SalesPersonID)
    ) = @GroupingLevel
ORDER BY
    GROUPING_ID(S.Name,H.SalesPersonID),GROUPING_ID((T.[Group])
    ,(T.CountryRegionCode)
    ,(S.Name)
    ,(H.SalesPersonID))ASC;

Example:

SELECT DATEPART(yyyy,OrderDate) AS N'Year'
    ,DATEPART(mm,OrderDate) AS N'Month'
    ,DATEPART(dd,OrderDate) AS N'Day'
    ,SUM(TotalDue) AS N'Total Due'
    ,CAST(GROUPING(DATEPART(dd,OrderDate)) AS CHAR(1)) +
        CAST(GROUPING(DATEPART(mm,OrderDate)) AS CHAR(1)) +
        CAST(GROUPING(DATEPART(yyyy,OrderDate)) AS CHAR(1))
     AS N'Bit Vector(base-2)'
    ,GROUPING_ID(DATEPART(yyyy,OrderDate)
        ,DATEPART(mm,OrderDate)
        ,DATEPART(dd,OrderDate))
        AS N'Integer Equivalent'
    ,CASE
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 0 THEN N'Year Month Day'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 1 THEN N'Year Month'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 2 THEN N'not used'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 3 THEN N'Year'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 4 THEN N'not used'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 5 THEN N'not used'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 6 THEN N'not used'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 7 THEN N'Grand Total'
    ELSE N'Error'
    END AS N'Grouping Level'
FROM Sales.SalesOrderHeader
WHERE DATEPART(yyyy,OrderDate) IN(N'2007',N'2008')
    AND DATEPART(mm,OrderDate) IN(1,2)
    AND DATEPART(dd,OrderDate) IN(1,2)
GROUP BY ROLLUP(DATEPART(yyyy,OrderDate)
        ,DATEPART(mm,OrderDate)
        ,DATEPART(dd,OrderDate))
ORDER BY GROUPING_ID(DATEPART(mm,OrderDate)
    ,DATEPART(yyyy,OrderDate)
    ,DATEPART(dd,OrderDate)
    )
    ,DATEPART(yyyy,OrderDate)
    ,DATEPART(mm,OrderDate)
    ,DATEPART(dd,OrderDate);

Example:

SELECT DATEPART(yyyy,OrderDate) AS N'Year'
    ,DATEPART(mm,OrderDate) AS N'Month'
    ,DATEPART(dd,OrderDate) AS N'Day'
    ,SUM(TotalDue) AS N'Total Due'
    ,CAST(GROUPING(DATEPART(dd,OrderDate)) AS CHAR(1)) +
        CAST(GROUPING(DATEPART(mm,OrderDate)) AS CHAR(1)) +
        CAST(GROUPING(DATEPART(yyyy,OrderDate)) AS CHAR(1))
        AS N'Bit Vector(base-2)'
    ,GROUPING_ID(DATEPART(yyyy,OrderDate)
        ,DATEPART(mm,OrderDate)
        ,DATEPART(dd,OrderDate))
        AS N'Integer Equivalent'
    ,CASE
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 0 THEN N'Year Month Day'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 1 THEN N'Year Month'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 2 THEN N'Year Day'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 3 THEN N'Year'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 4 THEN N'Month Day'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 5 THEN N'Month'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 6 THEN N'Day'
        WHEN GROUPING_ID(DATEPART(yyyy,OrderDate)
            ,DATEPART(mm,OrderDate),DATEPART(dd,OrderDate)
            ) = 7 THEN N'Grand Total'
    ELSE N'Error'
    END AS N'Grouping Level'
FROM Sales.SalesOrderHeader
WHERE DATEPART(yyyy,OrderDate) IN(N'2007',N'2008')
    AND DATEPART(mm,OrderDate) IN(1,2)
    AND DATEPART(dd,OrderDate) IN(1,2)
GROUP BY CUBE(DATEPART(yyyy,OrderDate)
    ,DATEPART(mm,OrderDate)
    ,DATEPART(dd,OrderDate))
ORDER BY GROUPING_ID(DATEPART(yyyy,OrderDate)
    ,DATEPART(mm,OrderDate)
    ,DATEPART(dd,OrderDate)
    )
    ,DATEPART(yyyy,OrderDate)
    ,DATEPART(mm,OrderDate)
    ,DATEPART(dd,OrderDate);

tan #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for tan

Syntax:

TAN ( float_expression )

Returns the tangent of the input expression.

Example:

SELECT TAN(PI()/2);

Example:

SELECT TAN(.45);

fileId #

Arguments

:: SExp

fileName'

-> SExp 

Origin documentation for fileId

Syntax:

FILE_ID ( file_name )

For the given logical name for a component file of the current database, this function returns the file identification (ID) number.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use FILE_IDEX instead.

Example:

USE AdventureWorks2012;
GO
SELECT FILE_ID('AdventureWorks2012_Data')AS 'File ID';
GO

dateName #

Arguments

:: SExp 
-> SExp

date

-> SExp 

Origin documentation for dateName

Syntax:

DATENAME ( datepart , date )

This function returns a character string representing the specified datepart of the specified date .

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SELECT DATENAME(year, '12:10:30.123')
    ,DATENAME(month, '12:10:30.123')
    ,DATENAME(day, '12:10:30.123')
    ,DATENAME(dayofyear, '12:10:30.123')
    ,DATENAME(weekday, '12:10:30.123');

Example:

DECLARE @t time = '12:10:30.123';
SELECT DATENAME(year, @t);

Example:

SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10');

__procid :: SExp #

Origin documentation for __procid

Syntax:

@@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.

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID ( 'usp_FindName', 'P' ) IS NOT NULL
DROP PROCEDURE usp_FindName;
GO
CREATE PROCEDURE usp_FindName
    @lastname VARCHAR(40) = '%',
    @firstname VARCHAR(20) = '%'
AS
DECLARE @Count INT;
DECLARE @ProcName NVARCHAR(128);
SELECT LastName, FirstName
FROM Person.Person
WHERE FirstName LIKE @firstname AND LastName LIKE @lastname;
SET @Count = @@ROWCOUNT;
SET @ProcName = OBJECT_NAME(@@PROCID);
RAISERROR ('Stored procedure %s returned %d rows.', 16,10, @ProcName, @Count);
GO
EXECUTE dbo.usp_FindName 'P%', 'A%';

sin #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for sin

Syntax:

SIN ( float_expression )

Returns the trigonometric sine of the specified angle, in radians, and in an approximate numeric, float , expression.

Example:

DECLARE @angle FLOAT;
SET @angle = 45.175643;
SELECT 'The SIN of the angle is: ' + CONVERT(VARCHAR, SIN(@angle));
GO

Example:

SELECT SIN(45.175643);

stuff #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

replacewithExpression

-> SExp 

Origin documentation for stuff

Syntax:

STUFF ( character_expression , start , length , replaceWith_expression )

The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

Example:

SELECT STUFF('abcdef', 2, 3, 'ijklmn');
GO

jsonPathExists #

Arguments

:: SExp 
-> SExp

sqlJsonPath

-> SExp 

Origin documentation for jsonPathExists

Syntax:

JSON_PATH_EXISTS( value_expression, sql_json_path )

Tests whether a specified SQL/JSON path exists in the input JSON string.

Example:

DECLARE @jsonInfo NVARCHAR(MAX)

SET @jsonInfo=N'{"info":{"address":[{"town":"Paris"},{"town":"London"}]}}';

SELECT JSON_PATH_EXISTS(@jsonInfo,'$.info.address'); -- 1

Example:

DECLARE @jsonInfo NVARCHAR(MAX)

SET @jsonInfo=N'{"info":{"address":[{"town":"Paris"},{"town":"London"}]}}';

SELECT JSON_PATH_EXISTS(@jsonInfo,'$.info.addresses'); -- 0

dateTimeFromParts #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

milliseconds

-> SExp 

Origin documentation for dateTimeFromParts

Syntax:

DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )

This function returns a datetime value for the specified date and time arguments.

Example:

SELECT DATETIMEFROMPARTS ( 2010, 12, 31, 23, 59, 59, 0 ) AS Result;

left #

Arguments

:: SExp 
-> SExp

integerExpression

-> SExp 

Origin documentation for left

Syntax:

LEFT ( character_expression , integer_expression )

Returns the left part of a character string with the specified number of characters.

Example:

SELECT LEFT(Name, 5)
FROM Production.Product
ORDER BY ProductID;
GO

Example:

SELECT LEFT('abcdefg',2);
GO

Example:

-- Uses AdventureWorks

SELECT LEFT(EnglishProductName, 5)
FROM dbo.DimProduct
ORDER BY ProductKey;

Example:

-- Uses AdventureWorks

SELECT LEFT('abcdefg',2) FROM dbo.DimProduct;

__totalErrors :: SExp #

Origin documentation for __totalErrors

Syntax:

@@TOTAL_ERRORS

Returns the number of disk write errors encountered by SQL Server since SQL Server last started.

Example:

SELECT @@TOTAL_ERRORS AS 'Errors', GETDATE() AS 'As of';

getDate :: SExp #

Origin documentation for getDate

Syntax:

GETDATE()

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.

Note

SYSDATETIME and SYSUTCDATETIME have more fractional seconds precision than GETDATE and GETUTCDATE. SYSDATETIMEOFFSET includes the system time zone offset. SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET can be assigned to a variable of any of the date and time types.

Azure SQL Database (with the exception of Azure SQL Managed Instance) and Azure Synapse Analytics follow UTC. Use AT TIME ZONE in Azure SQL Database or Azure Synapse Analytics if you need to interpret date and time information in a non-UTC time zone.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

DECLARE @dt datetimeoffset = switchoffset (CONVERT(datetimeoffset, GETDATE()), '-04:00');
SELECT * FROM t
WHERE c1 > @dt OPTION (RECOMPILE);

Example:

SELECT SYSDATETIME()
    ,SYSDATETIMEOFFSET()
    ,SYSUTCDATETIME()
    ,CURRENT_TIMESTAMP
    ,GETDATE()
    ,GETUTCDATE();

Example:

SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, SYSDATETIMEOFFSET())
    ,CONVERT (date, SYSUTCDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE())
    ,CONVERT (date, GETUTCDATE());

Example:

SELECT CONVERT (time, SYSDATETIME())
    ,CONVERT (time, SYSDATETIMEOFFSET())
    ,CONVERT (time, SYSUTCDATETIME())
    ,CONVERT (time, CURRENT_TIMESTAMP)
    ,CONVERT (time, GETDATE())
    ,CONVERT (time, GETUTCDATE());

Example:

SELECT SYSDATETIME()
    ,CURRENT_TIMESTAMP
    ,GETDATE();

Example:

SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE());

Example:

SELECT CONVERT (time, SYSDATETIME())
    ,CONVERT (time, CURRENT_TIMESTAMP)
    ,CONVERT (time, GETDATE());

currentRequestId :: SExp #

Origin documentation for currentRequestId

Syntax:

CURRENT_REQUEST_ID()

This function returns the ID of the current request within the current session.

certencoded #

Arguments

:: SExp

certId'

-> SExp 

Origin documentation for certencoded

Syntax:

CERTENCODED ( cert_id )

This function returns the public portion of a certificate in binary format. This function takes a certificate ID as an argument, and returns the encoded certificate. To create a new certificate, pass the binary result to CREATE CERTIFICATE ... WITH BINARY .

Example:

CREATE DATABASE TEST1;
GO
USE TEST1
CREATE CERTIFICATE Shipping04
ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y'
WITH SUBJECT = 'Sammamish Shipping Records',
EXPIRY_DATE = '20401031';
GO
SELECT CERTENCODED(CERT_ID('Shipping04'));

Example:

USE master;
GO
CREATE DATABASE SOURCE_DB;
GO
USE SOURCE_DB;
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'S0URCE_DB KEY Pa$$W0rd';
GO
CREATE DATABASE TARGET_DB;
GO
USE TARGET_DB
GO
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Pa$$W0rd in TARGET_DB';
GO

-- Create a certificate in SOURCE_DB
USE SOURCE_DB;
GO
CREATE CERTIFICATE SOURCE_CERT WITH SUBJECT = 'SOURCE_CERTIFICATE';
GO

Example:

DECLARE @CERTENC VARBINARY(MAX);
DECLARE @CERTPVK VARBINARY(MAX);
SELECT @CERTENC = CERTENCODED(CERT_ID('SOURCE_CERT'));
SELECT @CERTPVK = CERTPRIVATEKEY(CERT_ID('SOURCE_CERT'),
       'CertEncryptionPa$$word');
SELECT @CERTENC AS BinaryCertificate;
SELECT @CERTPVK AS EncryptedBinaryCertificate;
GO

Example:

-- Create the duplicate certificate in the TARGET_DB database
USE TARGET_DB
GO
CREATE CERTIFICATE TARGET_CERT
FROM BINARY = <insert the binary value of the @CERTENC variable>
WITH PRIVATE KEY (
BINARY = <insert the binary value of the @CERTPVK variable>
, DECRYPTION BY PASSWORD = 'CertEncryptionPa$$word');
-- Compare the certificates in the two databases
-- The two certificates should be the same
-- except for name and (possibly) the certificate_id
SELECT * FROM SOURCE_DB.sys.certificates
UNION
SELECT * FROM TARGET_DB.sys.certificates;

Example:

USE SOURCE_DB;

DECLARE @CLEARTEXT nvarchar(100);
DECLARE @CIPHERTEXT varbinary(8000);
DECLARE @UNCIPHEREDTEXT_Source nvarchar(100);
SET @CLEARTEXT = N'Hello World';
SET @CIPHERTEXT = ENCRYPTBYCERT(CERT_ID('SOURCE_CERT'), @CLEARTEXT);
SET @UNCIPHEREDTEXT_Source =
    DECRYPTBYCERT(CERT_ID('SOURCE_CERT'), @CIPHERTEXT)
-- Encryption and decryption result in SOURCE_DB
SELECT @CLEARTEXT AS SourceClearText, @CIPHERTEXT AS SourceCipherText,
       @UNCIPHEREDTEXT_Source AS SourceDecryptedText;

-- SWITCH DATABASE
USE TARGET_DB;

DECLARE @UNCIPHEREDTEXT_Target nvarchar(100);
SET @UNCIPHEREDTEXT_Target = DECRYPTBYCERT(CERT_ID('TARGET_CERT'), @CIPHERTEXT);
-- Encryption and decryption result in TARGET_DB
SELECT @CLEARTEXT AS ClearTextInTarget, @CIPHERTEXT AS CipherTextInTarget, @UNCIPHEREDTEXT_Target AS DecriptedTextInTarget;
GO

getBit #

Arguments

:: SExp 
-> SExp

bitOffset

-> SExp 

Origin documentation for getBit

Syntax:

GET_BIT ( expression_value, bit_offset )

GET_BIT takes two parameters and returns the bit in expression_value that is in the offset defined by bit_offset .

Example:

SELECT GET_BIT ( 0xabcdef, 2 ) as Get_2nd_Bit,
GET_BIT ( 0xabcdef, 4 ) as Get_4th_Bit;

month #

Arguments

:: SExp

date

-> SExp 

Origin documentation for month

Syntax:

MONTH ( date )

Returns an integer that represents the month of the specified date .

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

SELECT MONTH('2007-04-30T01:01:01.1234567 -07:00');

Example:

SELECT YEAR(0), MONTH(0), DAY(0);

Example:

-- Uses AdventureWorks

SELECT TOP 1 MONTH('2007-04-30T01:01:01.1234')
FROM dbo.DimCustomer;

Example:

-- Uses AdventureWorks

SELECT TOP 1 YEAR(0), MONTH(0), DAY(0) FROM dbo.DimCustomer;

checksum #

Arguments

:: NonEmpty SExp

expression

-> SExp 

Origin documentation for checksum

Syntax:

CHECKSUM ( * | expression [ ,...n ] )

The CHECKSUM function returns the checksum value computed over a table row, or over an expression list. Use CHECKSUM to build hash indexes.

Example:

-- Create a checksum index.

SET ARITHABORT ON;
USE AdventureWorks2012;
GO
ALTER TABLE Production.Product
ADD cs_Pname AS CHECKSUM(Name);
GO
CREATE INDEX Pname_index ON Production.Product (cs_Pname);
GO

Example:

/*Use the index in a SELECT query. Add a second search
condition to catch stray cases where checksums match,
but the values are not the same.*/

SELECT *
FROM Production.Product
WHERE CHECKSUM(N'Bearing Ball') = cs_Pname
AND Name = N'Bearing Ball';
GO

checksum_STAR :: SExp #

Origin documentation for checksum_STAR

Syntax:

CHECKSUM ( * | expression [ ,...n ] )

The CHECKSUM function returns the checksum value computed over a table row, or over an expression list. Use CHECKSUM to build hash indexes.

Example:

-- Create a checksum index.

SET ARITHABORT ON;
USE AdventureWorks2012;
GO
ALTER TABLE Production.Product
ADD cs_Pname AS CHECKSUM(Name);
GO
CREATE INDEX Pname_index ON Production.Product (cs_Pname);
GO

Example:

/*Use the index in a SELECT query. Add a second search
condition to catch stray cases where checksums match,
but the values are not the same.*/

SELECT *
FROM Production.Product
WHERE CHECKSUM(N'Bearing Ball') = cs_Pname
AND Name = N'Bearing Ball';
GO

switchOffset #

Arguments

:: SExp 
-> SExp

timezoneoffsetExpression

-> SExp 

Origin documentation for switchOffset

Syntax:

SWITCHOFFSET ( datetimeoffset_expression, timezoneoffset_expression )

Returns a datetimeoffset value that is changed from the stored time zone offset to a specified new time zone offset.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

DECLARE @dt datetimeoffset = switchoffset (CONVERT(datetimeoffset, GETDATE()), '-04:00');
SELECT * FROM t
WHERE c1 > @dt OPTION (RECOMPILE);

Example:

CREATE TABLE dbo.test
    (
    ColDatetimeoffset datetimeoffset
    );
GO
INSERT INTO dbo.test
VALUES ('1998-09-20 7:45:50.71345 -5:00');
GO
SELECT SWITCHOFFSET (ColDatetimeoffset, '-08:00')
FROM dbo.test;
GO
--Returns: 1998-09-20 04:45:50.7134500 -08:00
SELECT ColDatetimeoffset
FROM dbo.test;
--Returns: 1998-09-20 07:45:50.7134500 -05:00

encryptByAsymKey #

Arguments

:: SExp 
-> SExp

plaintext

-> SExp 

Origin documentation for encryptByAsymKey

Syntax:

EncryptByAsymKey ( Asym_Key_ID , { 'plaintext' | @plaintext } )

This function encrypts data with an asymmetric key.

Example:

INSERT INTO AdventureWorks2012.Sales.ProtectedData04
    VALUES( N'Data encrypted by asymmetric key ''JanainaAsymKey02''',
    EncryptByAsymKey(AsymKey_ID('JanainaAsymKey02'), @cleartext) );
GO

isNumeric #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for isNumeric

Syntax:

ISNUMERIC ( expression )

Determines whether an expression is a valid numeric type.

Example:

USE AdventureWorks2012;
GO
SELECT City, PostalCode
FROM Person.Address
WHERE ISNUMERIC(PostalCode) <> 1;
GO

Example:

USE master;
GO
SELECT name, ISNUMERIC(name) AS IsNameANumber, database_id, ISNUMERIC(database_id) AS IsIdANumber
FROM sys.databases;
GO

binaryChecksum #

Arguments

:: NonEmpty SExp

expression

-> SExp 

Origin documentation for binaryChecksum

Syntax:

BINARY_CHECKSUM ( * | expression [ ,...n ] )

Returns the binary checksum value computed over a row of a table or over a list of expressions.

Example:

USE AdventureWorks2012;
GO
CREATE TABLE myTable (column1 INT, column2 VARCHAR(256));
GO
INSERT INTO myTable VALUES (1, 'test');
GO
SELECT BINARY_CHECKSUM(*) from myTable;
GO
UPDATE myTable set column2 = 'TEST';
GO
SELECT BINARY_CHECKSUM(*) from myTable;
GO

binaryChecksum_STAR :: SExp #

Origin documentation for binaryChecksum_STAR

Syntax:

BINARY_CHECKSUM ( * | expression [ ,...n ] )

Returns the binary checksum value computed over a row of a table or over a list of expressions.

Example:

USE AdventureWorks2012;
GO
CREATE TABLE myTable (column1 INT, column2 VARCHAR(256));
GO
INSERT INTO myTable VALUES (1, 'test');
GO
SELECT BINARY_CHECKSUM(*) from myTable;
GO
UPDATE myTable set column2 = 'TEST';
GO
SELECT BINARY_CHECKSUM(*) from myTable;
GO

indexKeyProperty #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

property

-> SExp 

Origin documentation for indexKeyProperty

Syntax:

INDEXKEY_PROPERTY ( object_ID ,index_ID ,key_ID ,property )

Returns information about the index key. Returns NULL for XML indexes.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Instead, use sys.index_columns (Transact-SQL) .

Example:

USE AdventureWorks2012;
GO
SELECT
    INDEXKEY_PROPERTY(OBJECT_ID('Production.Location', 'U'),
        1,1,'ColumnId') AS [Column ID],
    INDEXKEY_PROPERTY(OBJECT_ID('Production.Location', 'U'),
        1,1,'IsDescending') AS [Asc or Desc order];

sysUtcDateTime :: SExp #

Origin documentation for sysUtcDateTime

Syntax:

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.

Note

SYSDATETIME and SYSUTCDATETIME have more fractional seconds precision than GETDATE and GETUTCDATE. SYSDATETIMEOFFSET includes the system time zone offset. SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET can be assigned to a variable of any one of the date and time types.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions .

Example:

SELECT SYSDATETIME() AS [SYSDATETIME()]
    ,SYSDATETIMEOFFSET() AS [SYSDATETIMEOFFSET()]
    ,SYSUTCDATETIME() AS [SYSUTCDATETIME()]
    ,CURRENT_TIMESTAMP AS [CURRENT_TIMESTAMP]
    ,GETDATE() AS [GETDATE()]
    ,GETUTCDATE() AS [GETUTCDATE()];

Example:

SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, SYSDATETIMEOFFSET())
    ,CONVERT (date, SYSUTCDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE())
    ,CONVERT (date, GETUTCDATE());

Example:

DECLARE @DATETIME DATETIME = GetDate();
DECLARE @TIME TIME
SELECT @TIME = CONVERT(time, @DATETIME)
SELECT @TIME AS 'Time', @DATETIME AS 'Date Time'

__totalRead :: SExp #

Origin documentation for __totalRead

Syntax:

@@TOTAL_READ

Returns the number of disk reads, not cache reads, by SQL Server since SQL Server was last started.

Example:

SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of';

originalDbName :: SExp #

Origin documentation for originalDbName

Syntax:

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 ).

This database is different from the default user database.

stdev #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for stdev

Syntax:

-- Aggregate Function Syntax
STDEV ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEV ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation of all values in the specified expression.

Example:

SELECT STDEV(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEV(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEV(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEV(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

__spid :: SExp #

Origin documentation for __spid

Syntax:

@@SPID

Returns the session ID of the current user process.

Example:

SELECT @@SPID AS 'ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name';

Example:

SELECT SESSION_ID() AS ID, @@SPID AS 'Control ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name';

jsonModify #

Arguments

:: SExp 
-> SExp 
-> SExp

newvalue

-> SExp 

Origin documentation for jsonModify

Syntax:

JSON_MODIFY ( expression , path , newValue )

Updates the value of a property in a JSON string and returns the updated JSON string.

Example:

DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'

PRINT @info

-- Update name

SET @info=JSON_MODIFY(@info,'$.name','Mike')

PRINT @info

-- Insert surname

SET @info=JSON_MODIFY(@info,'$.surname','Smith')

PRINT @info

-- Set name NULL

SET @info=JSON_MODIFY(@info,'strict $.name',NULL)

PRINT @info

-- Delete name

SET @info=JSON_MODIFY(@info,'$.name',NULL)

PRINT @info

-- Add skill

SET @info=JSON_MODIFY(@info,'append $.skills','Azure')

PRINT @info

Example:

DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'

PRINT @info

-- Multiple updates

SET @info=JSON_MODIFY(JSON_MODIFY(JSON_MODIFY(@info,'$.name','Mike'),'$.surname','Smith'),'append $.skills','Azure')

PRINT @info

Example:

DECLARE @product NVARCHAR(100)='{"price":49.99}'

PRINT @product

-- Rename property

SET @product=
 JSON_MODIFY(
  JSON_MODIFY(@product,'$.Price',CAST(JSON_VALUE(@product,'$.price') AS NUMERIC(4,2))),
  '$.price',
  NULL
 )

PRINT @product

Example:

DECLARE @stats NVARCHAR(100)='{"click_count": 173}'

PRINT @stats

-- Increment value

SET @stats=JSON_MODIFY(@stats,'$.click_count',
 CAST(JSON_VALUE(@stats,'$.click_count') AS INT)+1)

PRINT @stats

Example:

DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'

PRINT @info

-- Update skills array

SET @info=JSON_MODIFY(@info,'$.skills','["C#","T-SQL","Azure"]')

PRINT @info

Example:

DECLARE @info NVARCHAR(100)='{"name":"John","skills":["C#","SQL"]}'

PRINT @info

-- Update skills array

SET @info=JSON_MODIFY(@info,'$.skills',JSON_QUERY('["C#","T-SQL","Azure"]'))

PRINT @info

Example:

UPDATE Employee
SET jsonCol=JSON_MODIFY(jsonCol,'$.info.address.town','London')
WHERE EmployeeID=17

currentTransactionId :: SExp #

Origin documentation for currentTransactionId

Syntax:

CURRENT_TRANSACTION_ID( )

This function returns the transaction ID of the current transaction in the current session.

Example:

SELECT CURRENT_TRANSACTION_ID();

least #

Arguments

:: NonEmpty SExp

expression1

-> SExp 

Origin documentation for least

Syntax:

LEAST ( expression1 [ ,...expressionN ] )

This function returns the minimum value from a list of one or more expressions.

Example:

SELECT LEAST ( '6.62', 3.1415, N'7' ) AS LeastVal;
GO

Example:

SELECT LEAST ('Glacier', N'Joshua Tree', 'Mount Rainier') AS LeastString;
GO

Example:

SELECT P.Name, P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate AS ModelModifiedDate
    , LEAST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) AS EarliestDate
FROM SalesLT.Product AS P
INNER JOIN SalesLT.ProductModel AS PM on P.ProductModelID = PM.ProductModelID
WHERE LEAST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) >='2007-01-01'
AND P.SellStartDate >='2007-01-01'
AND P.Name LIKE 'Touring %'
ORDER BY P.Name;

Example:

CREATE TABLE dbo.studies (
    VarX varchar(10) NOT NULL,
    Correlation decimal(4, 3) NULL
);

INSERT INTO dbo.studies VALUES ('Var1', 0.2), ('Var2', 0.825), ('Var3', 0.61);
GO

DECLARE @PredictionA DECIMAL(2,1) = 0.7;
DECLARE @PredictionB DECIMAL(3,1) = 0.65;

SELECT VarX, Correlation
FROM dbo.studies
WHERE Correlation < LEAST(@PredictionA, @PredictionB);
GO

Example:

CREATE TABLE dbo.studies (
    VarX varchar(10) NOT NULL,
    Correlation decimal(4, 3) NULL
);

INSERT INTO dbo.studies VALUES ('Var1', 0.2), ('Var2', 0.825), ('Var3', 0.61);
GO

DECLARE @VarX decimal(4, 3) = 0.59;

SELECT VarX, Correlation, LEAST(Correlation, 1.0, @VarX) AS LeastVar
FROM dbo.studies;
GO

unicode #

Arguments

:: SExp

ncharacterExpression

-> SExp 

Origin documentation for unicode

Syntax:

UNICODE ( 'ncharacter_expression' )

Returns the integer value, as defined by the Unicode standard, for the first character of the input expression.

Example:

DECLARE @nstring NCHAR(12);
SET @nstring = N'Åkergatan 24';
SELECT UNICODE(@nstring), NCHAR(UNICODE(@nstring));

Example:

-- The @position variable holds the position of the character currently
-- being processed. The @nstring variable is the Unicode character
-- string to process.
DECLARE @position INT, @nstring NCHAR(12);
-- Initialize the current position variable to the first character in
-- the string.
SET @position = 1;
-- Initialize the character string variable to the string to process.
-- Notice that there is an N before the start of the string, which
-- indicates that the data following the N is Unicode data.
SET @nstring = N'Åkergatan 24';
-- Print the character number of the position of the string you are at,
-- the actual Unicode character you are processing, and the UNICODE
-- value for this particular character.
PRINT 'Character #' + ' ' + 'Unicode Character' + ' ' + 'UNICODE Value';
WHILE @position <= LEN(@nstring)
-- While these are still characters in the character string,

BEGIN;
   SELECT @position AS [position],
      SUBSTRING(@nstring, @position, 1) AS [character],
      UNICODE(SUBSTRING(@nstring, @position, 1)) AS [code_point];
   SET @position = @position + 1;
END;

cot #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for cot

Syntax:

COT ( float_expression )

A mathematical function that returns the trigonometric cotangent of the specified angle - in radians - in the specified float expression.

Example:

DECLARE @angle FLOAT;
SET @angle = 124.1332;
SELECT 'The COT of the angle is: ' + CONVERT(VARCHAR, COT(@angle));
GO

isObjectSigned #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

thumbprint

-> SExp 

Origin documentation for isObjectSigned

Syntax:

IS_OBJECTSIGNED (
'OBJECT', @object_id, @class, @thumbprint
  )

Indicates whether an object is signed by a specified certificate or asymmetric key.

Example:

USE master;
-- Declare a variable to hold a thumbprint and an object name
DECLARE @thumbprint varbinary(20), @objectname sysname;

-- Populate the thumbprint variable with the thumbprint of
-- the master database schema signing certificate
SELECT @thumbprint = thumbprint
FROM sys.certificates
WHERE name LIKE '%SchemaSigningCertificate%';

-- Populate the object name variable with a table name in master
SELECT @objectname = 'spt_fallback_db';

-- Query to see if the table is signed by the thumbprint
SELECT @objectname AS [object name],
IS_OBJECTSIGNED(
'OBJECT', OBJECT_ID(@objectname), 'certificate', @thumbprint
) AS [Is the object signed?] ;

__remserver :: SExp #

Origin documentation for __remserver

Syntax:

@@REMSERVER

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. This function exists for backward compatibility and always returns NULL. Use linked servers and linked server stored procedures instead.

Returns the name of the remote SQL Server database server as it appears in the login record.

Example:

CREATE PROCEDURE usp_CheckServer
AS
SELECT @@REMSERVER;

Example:

EXEC SEATTLE1...usp_CheckServer;

degrees #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for degrees

Syntax:

DEGREES ( numeric_expression )

This function returns the corresponding angle, in degrees, for an angle specified in radians.

Example:

SELECT 'The number of degrees in PI/2 radians is: ' +
CONVERT(VARCHAR, DEGREES((PI()/2)));
GO

__NestLevel :: SExp #

Origin documentation for __NestLevel

Syntax:

@@NESTLEVEL

Returns the nesting level of the current stored procedure execution (initially 0) on the local server.

Example:

USE AdventureWorks2012;
GO
IF OBJECT_ID (N'usp_OuterProc', N'P')IS NOT NULL
    DROP PROCEDURE usp_OuterProc;
GO
IF OBJECT_ID (N'usp_InnerProc', N'P')IS NOT NULL
    DROP PROCEDURE usp_InnerProc;
GO
CREATE PROCEDURE usp_InnerProc AS
    SELECT @@NESTLEVEL AS 'Inner Level';
GO
CREATE PROCEDURE usp_OuterProc AS
    SELECT @@NESTLEVEL AS 'Outer Level';
    EXEC usp_InnerProc;
GO
EXECUTE usp_OuterProc;
GO

Example:

CREATE PROC usp_NestLevelValues AS
    SELECT @@NESTLEVEL AS 'Current Nest Level';
EXEC ('SELECT @@NESTLEVEL AS OneGreater');
EXEC sp_executesql N'SELECT @@NESTLEVEL as TwoGreater' ;
GO
EXEC usp_NestLevelValues;
GO

textptr #

Arguments

:: SExp

column

-> SExp 

Origin documentation for textptr

Syntax:

TEXTPTR ( column )

Returns the text-pointer value that corresponds to a text , ntext , or image column in varbinary format. The retrieved text pointer value can be used in READTEXT, WRITETEXT, and UPDATETEXT statements.

Important

This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Alternative functionality is not available.

Example:

USE pubs;
GO
DECLARE @ptrval VARBINARY(16);
SELECT @ptrval = TEXTPTR(logo)
FROM pub_info pr, publishers p
WHERE p.pub_id = pr.pub_id
   AND p.pub_name = 'New Moon Books';
GO

Example:

CREATE TABLE t1 (c1 INT, c2 TEXT);
EXEC sp_tableoption 't1', 'text in row', 'on';
INSERT t1 VALUES ('1', 'This is text.');
GO
BEGIN TRAN;
   DECLARE @ptrval VARBINARY(16);
   SELECT @ptrval = TEXTPTR(c2)
   FROM t1
   WHERE c1 = 1;
   READTEXT t1.c2 @ptrval 0 1;
COMMIT;

Example:

USE pubs;
GO
SELECT pub_id, TEXTPTR(pr_info)
FROM pub_info
ORDER BY pub_id;
GO

Example:

USE pubs;
GO
SET TEXTSIZE 8000;
SELECT pub_id, pr_info
FROM pub_info
ORDER BY pub_id;
GO

Example:

USE pubs;
GO
DECLARE @val VARBINARY(16);
SELECT @val = TEXTPTR(pr_info)
FROM pub_info
WHERE pub_id = '0736';
READTEXT pub_info.pr_info @val 4 10;
GO

grouping #

Arguments

:: SExp

columnExpression

-> SExp 

Origin documentation for grouping

Syntax:

GROUPING ( <column_expression> )

Indicates whether a specified column expression in a GROUP BY list is aggregated or not. GROUPING returns 1 for aggregated or 0 for not aggregated in the result set. GROUPING can be used only in the SELECT select list, HAVING, and ORDER BY clauses when GROUP BY is specified.

Example:

SELECT SalesQuota, SUM(SalesYTD) 'TotalSalesYTD', GROUPING(SalesQuota) AS 'Grouping'
FROM Sales.SalesPerson
GROUP BY SalesQuota WITH ROLLUP;
GO

sessionContext #

Arguments

:: SExp

key

-> SExp 

Origin documentation for sessionContext

Syntax:

SESSION_CONTEXT(N'key')

Returns the value of the specified key in the current session context. The value is set by using the sp_set_session_context (Transact-SQL) procedure.

Example:

EXEC sp_set_session_context 'user_id', 4;
SELECT SESSION_CONTEXT(N'user_id');

sessionId :: SExp #

Origin documentation for sessionId

Syntax:

-- Azure Synapse Analytics and Parallel Data Warehouse
SESSION_ID ( )

Returns the ID of the current Azure Synapse Analytics or Analytics Platform System (PDW) session.

Example:

SELECT SESSION_ID();

eventdata :: SExp #

Origin documentation for eventdata

Syntax:

EVENTDATA( )

This function returns information about server or database events. When an event notification fires, and the specified service broker receives the results, EVENTDATA is called. A DDL or logon trigger also support internal use of EVENTDATA .

Example:

USE AdventureWorks2012;
GO
CREATE TRIGGER safety
ON DATABASE
FOR CREATE_TABLE
AS
    PRINT 'CREATE TABLE Issued.'
    SELECT EVENTDATA().value
        ('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
   RAISERROR ('New tables cannot be created in this database.', 16, 1)
   ROLLBACK
;
GO
--Test the trigger.
CREATE TABLE NewTable (Column1 INT);
GO
--Drop the trigger.
DROP TRIGGER safety
ON DATABASE;
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE ddl_log (PostTime DATETIME, DB_User NVARCHAR(100), Event NVARCHAR(100), TSQL NVARCHAR(2000));
GO
CREATE TRIGGER log
ON DATABASE
FOR DDL_DATABASE_LEVEL_EVENTS
AS
DECLARE @data XML
SET @data = EVENTDATA()
INSERT ddl_log
   (PostTime, DB_User, Event, TSQL)
   VALUES
   (GETDATE(),
   CONVERT(NVARCHAR(100), CURRENT_USER),
   @data.value('(/EVENT_INSTANCE/EventType)[1]', 'NVARCHAR(100)'),
   @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'NVARCHAR(2000)') ) ;
GO
--Test the trigger.
CREATE TABLE TestTable (a INT);
DROP TABLE TestTable ;
GO
SELECT * FROM ddl_log ;
GO
--Drop the trigger.
DROP TRIGGER log
ON DATABASE;
GO
--Drop table ddl_log.
DROP TABLE ddl_log;
GO

__langid :: SExp #

Origin documentation for __langid

Syntax:

@@LANGID

Returns the local language identifier (ID) of the language that is currently being used.

Example:

SET LANGUAGE 'Italian'
SELECT @@LANGID AS 'Language ID'

log10 #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for log10

Syntax:

LOG10 ( float_expression )

Returns the base-10 logarithm of the specified float expression.

Example:

DECLARE @var FLOAT;
SET @var = 145.175643;
SELECT 'The LOG10 of the variable is: ' + CONVERT(VARCHAR,LOG10(@var));
GO

Example:

SELECT POWER (10, LOG10(5));

Example:

SELECT LOG10(145.175642);

dataLength #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for dataLength

Syntax:

DATALENGTH ( expression )

This function returns the number of bytes used to represent any expression.

Note

To return the number of characters in a string expression, use the LEN function.

Example:

USE AdventureWorks2016
GO
SELECT length = DATALENGTH(EnglishProductName), EnglishProductName
FROM dbo.DimProduct
ORDER BY EnglishProductName;
GO

originalLogin :: SExp #

Origin documentation for originalLogin

Syntax:

ORIGINAL_LOGIN( )

Returns the name of the login that connected to the instance of SQL Server. You can use this function to return the identity of the original login in sessions in which there are many explicit or implicit context switches.

Example:

USE AdventureWorks2012;
GO
--Create a temporary login and user.
CREATE LOGIN login1 WITH PASSWORD = 'J345#$)thb';
CREATE USER user1 FOR LOGIN login1;
GO
--Execute a context switch to the temporary login account.
DECLARE @original_login sysname;
DECLARE @current_context sysname;
EXECUTE AS LOGIN = 'login1';
SET @original_login = ORIGINAL_LOGIN();
SET @current_context = SUSER_SNAME();
SELECT 'The current executing context is: '+ @current_context;
SELECT 'The original login in this session was: '+ @original_login
GO
-- Return to the original execution context
-- and remove the temporary principal.
REVERT;
GO
DROP LOGIN login1;
DROP USER user1;
GO

databasePrincipalId #

Arguments

:: SExp

principalName

-> SExp 

Origin documentation for databasePrincipalId

Syntax:

DATABASE_PRINCIPAL_ID ( 'principal_name' )

This function returns the ID number of a principal in the current database. See Principals (Database Engine) for more information about principals.

Example:

SELECT DATABASE_PRINCIPAL_ID();
GO

Example:

SELECT DATABASE_PRINCIPAL_ID('db_owner');
GO

toDateTimeOffset #

Arguments

:: SExp 
-> SExp

timezoneoffsetExpression

-> SExp 

Origin documentation for toDateTimeOffset

Syntax:

TODATETIMEOFFSET ( datetime_expression , timezoneoffset_expression )

Returns a datetimeoffset value that is translated from a datetime2 expression.

Example:

DECLARE @todaysDateTime DATETIME2;
SET @todaysDateTime = GETDATE();
SELECT TODATETIMEOFFSET (@todaysDateTime, '-07:00');
-- RETURNS 2019-04-22 16:23:51.7666667 -07:00

Example:

SELECT TODATETIMEOFFSET(SYSDATETIME(), -120)
-- RETURNS: 2019-04-22 11:39:21.6986813 -02:00

Example:

SELECT TODATETIMEOFFSET(SYSDATETIME(), '+13:00')
-- RETURNS: 2019-04-22 11:39:29.0339301 +13:00

fulltextserviceProperty #

Arguments

:: SExp

property

-> SExp 

Origin documentation for fulltextserviceProperty

Syntax:

FULLTEXTSERVICEPROPERTY ('property')

Returns information related to the properties of the Full-Text Engine. These properties can be set and retrieved by using sp_fulltext_service .

Example:

SELECT fulltextserviceproperty('VerifySignature');

Example:

EXEC sp_fulltext_service @action='verify_signature', @value=1;
GO

newid :: SExp #

Origin documentation for newid

Syntax:

NEWID ( )

Creates a unique value of type uniqueidentifier .

Example:

-- Creating a local variable with DECLARE/SET syntax.
DECLARE @myid uniqueidentifier
SET @myid = NEWID()
PRINT 'Value of @myid is: '+ CONVERT(varchar(255), @myid)

Example:

-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
 CustomerID uniqueidentifier NOT NULL
   DEFAULT newid(),
 Company VARCHAR(30) NOT NULL,
 ContactName VARCHAR(60) NOT NULL,
 Address VARCHAR(30) NOT NULL,
 City VARCHAR(30) NOT NULL,
 StateProvince VARCHAR(10) NULL,
 PostalCode VARCHAR(10) NOT NULL,
 CountryRegion VARCHAR(20) NOT NULL,
 Telephone VARCHAR(15) NOT NULL,
 Fax VARCHAR(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(Company, ContactName, Address, City, StateProvince,
 PostalCode, CountryRegion, Telephone, Fax)
VALUES
 ('Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
 '90110', 'Finland', '981-443655', '981-443655')
,('Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
 '08737-363', 'Brasil', '(14) 555-8122', '')
,('Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,('Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
 '8010', 'Austria', '7675-3425', '7675-3426')
,('Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO

Example:

DECLARE @myid uniqueidentifier ;
SET @myid = 'A972C577-DFB0-064E-1189-0154C99310DAAC12';
SELECT @myid;
GO

leftShift #

Arguments

:: SExp 
-> SExp

shiftAmount

-> SExp 

Origin documentation for leftShift

Syntax:

LEFT_SHIFT ( expression_value, shift_amount )
expression_value << shift_amount

LEFT_SHIFT takes two parameters, and returns the first parameter bit-shifted left by the number of bits specified in the second parameter.

The LEFT_SHIFT function is also accessible through the << operator.

Example:

SELECT LEFT_SHIFT(12345, 5);

floor #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for floor

Syntax:

FLOOR ( numeric_expression )

Returns the largest integer less than or equal to the specified numeric expression.

Example:

SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45);

Example:

SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45);

minActiveRowVersion :: SExp #

Origin documentation for minActiveRowVersion

Syntax:

MIN_ACTIVE_ROWVERSION ( )

Returns the lowest active rowversion value in the current database. A rowversion value is active if it is used in a transaction that has not yet been committed. For more information, see rowversion (Transact-SQL) .

Note

The rowversion data type is also known as timestamp .

Example:

-- Create a table that has a ROWVERSION column in it.
CREATE TABLE RowVersionTestTable (rv ROWVERSION)
GO

-- Print the current values for the database.
PRINT ''
PRINT 'DBTS'
PRINT @@DBTS
PRINT 'MIN_ACTIVE_ROWVERSION'
PRINT MIN_ACTIVE_ROWVERSION()
GO
---------------- Results ----------------
--DBTS
--0x00000000000007E2
--MIN_ACTIVE_ROWVERSION
--0x00000000000007E3

-- Insert a row.
INSERT INTO RowVersionTestTable VALUES (DEFAULT)
SELECT * FROM RowVersionTestTable
GO
---------------- Results ----------------
--rv
--0x00000000000007E3

-- Print the current values for the database.
PRINT ''
PRINT 'DBTS'
PRINT @@DBTS
PRINT 'MIN_ACTIVE_ROWVERSION'
PRINT MIN_ACTIVE_ROWVERSION()
GO
---------------- Results ----------------
--DBTS
--0x00000000000007E3
--MIN_ACTIVE_ROWVERSION
--0x00000000000007E4

-- Insert a new row inside a transaction but do not commit.
BEGIN TRAN
INSERT INTO RowVersionTestTable VALUES (DEFAULT)
SELECT * FROM RowVersionTestTable
GO
---------------- Results ----------------
--rv
--0x00000000000007E3
--0x00000000000007E4

-- Print the current values for the database.
PRINT ''
PRINT 'DBTS'
PRINT @@DBTS
PRINT 'MIN_ACTIVE_ROWVERSION'
PRINT MIN_ACTIVE_ROWVERSION()
GO
---------------- Results ----------------
--DBTS
--0x00000000000007E4
--MIN_ACTIVE_ROWVERSION
--0x00000000000007E4

-- Commit the transaction.
COMMIT
GO

-- Print the current values for the database.
PRINT ''
PRINT 'DBTS'
PRINT @@DBTS
PRINT 'MIN_ACTIVE_ROWVERSION'
PRINT MIN_ACTIVE_ROWVERSION()
GO
---------------- Results ----------------
--DBTS
--0x00000000000007E4
--MIN_ACTIVE_ROWVERSION
--0x00000000000007E5

jsonValue #

Arguments

:: SExp 
-> SExp

path

-> SExp 

Origin documentation for jsonValue

Syntax:

JSON_VALUE ( expression , path )

Extracts a scalar value from a JSON string.

To extract an object or an array from a JSON string instead of a scalar value, see JSON_QUERY (Transact-SQL) . For info about the differences between JSON_VALUE and JSON_QUERY , see Compare JSON_VALUE and JSON_QUERY .

Example:

SELECT FirstName, LastName,
 JSON_VALUE(jsonInfo,'$.info.address.town') AS Town
FROM Person.Person
WHERE JSON_VALUE(jsonInfo,'$.info.address.state') LIKE 'US%'
ORDER BY JSON_VALUE(jsonInfo,'$.info.address.town')

Example:

DECLARE @jsonInfo NVARCHAR(MAX)
DECLARE @town NVARCHAR(32)

SET @jsonInfo=N'{"info":{"address":[{"town":"Paris"},{"town":"London"}]}}';

SET @town=JSON_VALUE(@jsonInfo,'$.info.address[0].town'); -- Paris
SET @town=JSON_VALUE(@jsonInfo,'$.info.address[1].town'); -- London

Example:

CREATE TABLE dbo.Store
 (
  StoreID INT IDENTITY(1,1) NOT NULL,
  Address VARCHAR(500),
  jsonContent NVARCHAR(4000),
  Longitude AS JSON_VALUE(jsonContent, '$.address[0].longitude'),
  Latitude AS JSON_VALUE(jsonContent, '$.address[0].latitude')
 )

isDate #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for isDate

Syntax:

ISDATE ( expression )

Returns 1 if the expression is a valid datetime value; otherwise, 0.

ISDATE returns 0 if the expression is a datetime2 value.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) . Note that the range for datetime data is 1753-01-01 through 9999-12-31, while the range for date data is 0001-01-01 through 9999-12-31.

Example:

IF ISDATE('2009-05-12 10:19:41.177') = 1
    PRINT 'VALID'
ELSE
    PRINT 'INVALID';

Example:

/* Use these sessions settings. */
SET LANGUAGE us_english;
SET DATEFORMAT mdy;
/* Expression in mdy dateformat */
SELECT ISDATE('04/15/2008'); --Returns 1.
/* Expression in mdy dateformat */
SELECT ISDATE('04-15-2008'); --Returns 1.
/* Expression in mdy dateformat */
SELECT ISDATE('04.15.2008'); --Returns 1.
/* Expression in myd  dateformat */
SELECT ISDATE('04/2008/15'); --Returns 1.

SET DATEFORMAT mdy;
SELECT ISDATE('15/04/2008'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('15/2008/04'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('2008/15/04'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('2008/04/15'); --Returns 1.

SET DATEFORMAT dmy;
SELECT ISDATE('15/04/2008'); --Returns 1.
SET DATEFORMAT dym;
SELECT ISDATE('15/2008/04'); --Returns 1.
SET DATEFORMAT ydm;
SELECT ISDATE('2008/15/04'); --Returns 1.
SET DATEFORMAT ymd;
SELECT ISDATE('2008/04/15'); --Returns 1.

SET LANGUAGE English;
SELECT ISDATE('15/04/2008'); --Returns 0.
SET LANGUAGE Hungarian;
SELECT ISDATE('15/2008/04'); --Returns 0.
SET LANGUAGE Swedish;
SELECT ISDATE('2008/15/04'); --Returns 0.
SET LANGUAGE Italian;
SELECT ISDATE('2008/04/15'); --Returns 1.

/* Return to these sessions settings. */
SET LANGUAGE us_english;
SET DATEFORMAT mdy;

Example:

IF ISDATE('2009-05-12 10:19:41.177') = 1
    SELECT 'VALID';
ELSE
    SELECT 'INVALID';

__cpuBusy :: SExp #

Origin documentation for __cpuBusy

Syntax:

@@CPU_BUSY

This function returns the amount of time that SQL Server has spent in active operation since its latest start. @@CPU_BUSY returns a result measured in CPU time increments, or "ticks." This value is cumulative for all CPUs, so it may exceed the actual elapsed time. To convert to microseconds, multiply by @@TIMETICKS .

Note

If the time returned in @CPU_BUSY or IO_BUSY exceeds 49 days (approximately) of cumulative CPU time, you may receive an arithmetic overflow warning. In that case, the value of the @CPU_BUSY , @@IO_BUSY and @@IDLE variables are not accurate.

Example:

SELECT @@CPU_BUSY * CAST(@@TIMETICKS AS FLOAT) AS 'CPU microseconds',
   GETDATE() AS 'As of' ;

getUtcDate :: SExp #

Origin documentation for getUtcDate

Syntax:

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.

Note

SYSDATETIME and SYSUTCDATETIME have more fractional seconds precision than GETDATE and GETUTCDATE. SYSDATETIMEOFFSET includes the system time zone offset. SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET can be assigned to a variable of any of the date and time types.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

SELECT 'SYSDATETIME()      ', SYSDATETIME();
SELECT 'SYSDATETIMEOFFSET()', SYSDATETIMEOFFSET();
SELECT 'SYSUTCDATETIME()   ', SYSUTCDATETIME();
SELECT 'CURRENT_TIMESTAMP  ', CURRENT_TIMESTAMP;
SELECT 'GETDATE()          ', GETDATE();
SELECT 'GETUTCDATE()       ', GETUTCDATE();
/* Returned:
SYSDATETIME()            2007-05-03 18:34:11.9351421
SYSDATETIMEOFFSET()      2007-05-03 18:34:11.9351421 -07:00
SYSUTCDATETIME()         2007-05-04 01:34:11.9351421
CURRENT_TIMESTAMP        2007-05-03 18:34:11.933
GETDATE()                2007-05-03 18:34:11.933
GETUTCDATE()             2007-05-04 01:34:11.933
*/

Example:

SELECT 'SYSDATETIME()      ', CONVERT (time, SYSDATETIME());
SELECT 'SYSDATETIMEOFFSET()', CONVERT (time, SYSDATETIMEOFFSET());
SELECT 'SYSUTCDATETIME()   ', CONVERT (time, SYSUTCDATETIME());
SELECT 'CURRENT_TIMESTAMP  ', CONVERT (time, CURRENT_TIMESTAMP);
SELECT 'GETDATE()          ', CONVERT (time, GETDATE());
SELECT 'GETUTCDATE()       ', CONVERT (time, GETUTCDATE());
/* Returned
SYSDATETIME()            18:25:01.6958841
SYSDATETIMEOFFSET()      18:25:01.6958841
SYSUTCDATETIME()         01:25:01.6958841
CURRENT_TIMESTAMP        18:25:01.6930000
GETDATE()                18:25:01.6930000
GETUTCDATE()             01:25:01.6930000
*/

statsDate #

Arguments

:: SExp 
-> SExp

statsId

-> SExp 

Origin documentation for statsDate

Syntax:

STATS_DATE ( object_id , stats_id )

Returns the date of the most recent update for statistics on a table or indexed view.

For more information about updating statistics, see Statistics .

Example:

USE AdventureWorks2012;
GO
SELECT name AS stats_name,
    STATS_DATE(object_id, stats_id) AS statistics_update_date
FROM sys.stats
WHERE object_id = OBJECT_ID('Person.Address');
GO

Example:

USE AdventureWorks2012;
GO
SELECT name AS index_name,
    STATS_DATE(object_id, index_id) AS statistics_update_date
FROM sys.indexes
WHERE object_id = OBJECT_ID('Person.Address');
GO

Example:

--First, create a statistics object
USE AdventureWorksPDW2012;
GO
CREATE STATISTICS Customer_LastName_Stats
ON AdventureWorksPDW2012.dbo.DimCustomer (LastName)
WITH SAMPLE 50 PERCENT;
GO

--Return the date when Customer_LastName_Stats was last updated
USE AdventureWorksPDW2012;
GO
SELECT stats_id, name AS stats_name,
    STATS_DATE(object_id, stats_id) AS statistics_date
FROM sys.stats s
WHERE s.object_id = OBJECT_ID('dbo.DimCustomer')
    AND s.name = 'Customer_LastName_Stats';
GO

--Update Customer_LastName_Stats so it will have a different timestamp in the next query
GO
UPDATE STATISTICS dbo.dimCustomer (Customer_LastName_Stats);

--Return the date when Customer_LastName_Stats was last updated.
SELECT stats_id, name AS stats_name,
    STATS_DATE(object_id, stats_id) AS statistics_date
FROM sys.stats s
WHERE s.object_id = OBJECT_ID('dbo.DimCustomer')
    AND s.name = 'Customer_LastName_Stats';
GO

Example:

--Return the dates all statistics on the table were last updated.
SELECT stats_id, name AS stats_name,
    STATS_DATE(object_id, stats_id) AS statistics_date
FROM sys.stats s
WHERE s.object_id = OBJECT_ID('dbo.DimCustomer');
GO

Example:

USE AdventureWorksPDW2012;
GO
SELECT name AS index_name,
    STATS_DATE(object_id, index_id) AS statistics_update_date
FROM sys.indexes
WHERE object_id = OBJECT_ID('dbo.DimCustomer');
GO

__serviceName :: SExp #

Origin documentation for __serviceName

Syntax:

@@SERVICENAME

Returns the name of the registry key under which SQL Server is running. @@SERVICENAME returns MSSQLSERVER if the current instance is the default instance; this function returns the instance name if the current instance is a named instance.

Example:

SELECT @@SERVICENAME AS 'Service Name';

identSeed #

Arguments

:: SExp

tableOrView

-> SExp 

Origin documentation for identSeed

Syntax:

IDENT_SEED ( 'table_or_view' )

Returns the original seed value specified when creating an identity column in a table or a view. Changing the current value of an identity column by using DBCC CHECKIDENT doesn't change the value returned by this function.

Example:

USE AdventureWorks2012;
GO
SELECT IDENT_SEED('Person.Address') AS Identity_Seed;
GO

Example:

USE AdventureWorks2012;
GO
SELECT TABLE_SCHEMA, TABLE_NAME,
   IDENT_SEED(TABLE_SCHEMA + '.' + TABLE_NAME) AS IDENT_SEED
FROM INFORMATION_SCHEMA.TABLES
WHERE IDENT_SEED(TABLE_SCHEMA + '.' + TABLE_NAME) IS NOT NULL;
GO

__textsize :: SExp #

Origin documentation for __textsize

Syntax:

@@TEXTSIZE

Returns the current value of the TEXTSIZE option.

Example:

-- Set the TEXTSIZE option to the default size of 4096 bytes.
SET TEXTSIZE 0
SELECT @@TEXTSIZE AS 'Text Size'
SET TEXTSIZE 2048
SELECT @@TEXTSIZE AS 'Text Size'

smallDateTimeFromParts #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp 
-> SExp

minute

-> SExp 

Origin documentation for smallDateTimeFromParts

Syntax:

SMALLDATETIMEFROMPARTS ( year, month, day, hour, minute )

Returns a smalldatetime value for the specified date and time.

Example:

SELECT SMALLDATETIMEFROMPARTS ( 2010, 12, 31, 23, 59 ) AS Result

sessionProperty #

Arguments

:: SExp

option

-> SExp 

Origin documentation for sessionProperty

Syntax:

SESSIONPROPERTY (option)

Returns the SET options settings of a session.

Example:

SELECT   SESSIONPROPERTY ('CONCAT_NULL_YIELDS_NULL')

xactState :: SExp #

Origin documentation for xactState

Syntax:

XACT_STATE()

Is a scalar function that reports the user transaction state of a current running request. XACT_STATE indicates whether the request has an active user transaction, and whether the transaction is capable of being committed.

Example:

USE AdventureWorks2012;
GO

-- SET XACT_ABORT ON will render the transaction uncommittable
-- when the constraint violation occurs.
SET XACT_ABORT ON;

BEGIN TRY
    BEGIN TRANSACTION;
        -- A FOREIGN KEY constraint exists on this table. This
        -- statement will generate a constraint violation error.
        DELETE FROM Production.Product
            WHERE ProductID = 980;

    -- If the delete operation succeeds, commit the transaction. The CATCH
    -- block will not execute.
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    -- Test XACT_STATE for 0, 1, or -1.
    -- If 1, the transaction is committable.
    -- If -1, the transaction is uncommittable and should
    --     be rolled back.
    -- XACT_STATE = 0 means there is no transaction and
    --     a commit or rollback operation would generate an error.

    -- Test whether the transaction is uncommittable.
    IF (XACT_STATE()) = -1
    BEGIN
        PRINT 'The transaction is in an uncommittable state.' +
              ' Rolling back transaction.'
        ROLLBACK TRANSACTION;
    END;

    -- Test whether the transaction is active and valid.
    IF (XACT_STATE()) = 1
    BEGIN
        PRINT 'The transaction is committable.' +
              ' Committing transaction.'
        COMMIT TRANSACTION;
    END;
END CATCH;
GO

checksumAgg #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for checksumAgg

Syntax:

CHECKSUM_AGG ( [ ALL | DISTINCT ] expression )

This function returns the checksum of the values in a group. CHECKSUM_AGG ignores null values. The OVER clause can follow CHECKSUM_AGG .

Example:

--Get the checksum value before the column value is changed.

SELECT CHECKSUM_AGG(CAST(Quantity AS INT))
FROM Production.ProductInventory;
GO

Example:

UPDATE Production.ProductInventory
SET Quantity=125
WHERE Quantity=100;
GO

--Get the checksum of the modified column.
SELECT CHECKSUM_AGG(CAST(Quantity AS INT))
FROM Production.ProductInventory;

decompress #

Arguments

:: SExp

expression

-> SExp 

Origin documentation for decompress

Syntax:

DECOMPRESS ( expression )

This function will decompress an input expression value, using the GZIP algorithm. DECOMPRESS will return a byte array (VARBINARY(MAX) type).

Example:

SELECT _id, name, surname, datemodified,
             CAST(DECOMPRESS(info) AS NVARCHAR(MAX)) AS info
FROM player;

Example:

CREATE TABLE example_table (
    _id INT PRIMARY KEY IDENTITY,
    name NVARCHAR(max),
    surname NVARCHAR(max),
    info VARBINARY(max),
    info_json as CAST(DECOMPRESS(info) as NVARCHAR(max))
);

replace #

Arguments

:: SExp 
-> SExp 
-> SExp

stringReplacement

-> SExp 

Origin documentation for replace

Syntax:

REPLACE ( string_expression , string_pattern , string_replacement )

Replaces all occurrences of a specified string value with another string value.

Example:

SELECT REPLACE('abcdefghicde','cde','xxx');
GO

Example:

SELECT REPLACE('This is a Test'  COLLATE Latin1_General_BIN,
'Test', 'desk' );
GO

Example:

DECLARE @STR NVARCHAR(100), @LEN1 INT, @LEN2 INT;
SET @STR = N'This is a sentence with spaces in it.';
SET @LEN1 = LEN(@STR);
SET @STR = REPLACE(@STR, N' ', N'');
SET @LEN2 = LEN(@STR);
SELECT N'Number of spaces in the string: ' + CONVERT(NVARCHAR(20), @LEN1 - @LEN2);

GO

space #

Arguments

:: SExp

integerExpression

-> SExp 

Origin documentation for space

Syntax:

SPACE ( integer_expression )

Returns a string of repeated spaces.

Example:

USE AdventureWorks2012;
GO
SELECT RTRIM(LastName) + ',' + SPACE(2) +  LTRIM(FirstName)
FROM Person.Person
ORDER BY LastName, FirstName;
GO

Example:

-- Uses AdventureWorks

SELECT RTRIM(LastName) + ',' + SPACE(2) +  LTRIM(FirstName)
FROM dbo.DimCustomer
ORDER BY LastName, FirstName;
GO

connectionProperty #

Arguments

:: SExp

property

-> SExp 

Origin documentation for connectionProperty

Syntax:

CONNECTIONPROPERTY ( property )

For a request that comes in to the server, this function returns information about the connection properties of the unique connection which supports that request.

Example:

SELECT
ConnectionProperty('net_transport') AS 'Net transport',
ConnectionProperty('protocol_type') AS 'Protocol type';

version :: SExp #

Origin documentation for version

Syntax:

-- Azure Synapse Analytics and Parallel Data Warehouse
VERSION ( )

Returns the version of Azure Synapse Analytics or Analytics Platform System (PDW) running on the appliance.

Example:

SELECT VERSION();

objectProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for objectProperty

Syntax:

OBJECTPROPERTY ( id , property )

Returns information about schema-scoped objects in the current database. For a list of schema-scoped objects, see sys.objects (Transact-SQL) . This function cannot be used for objects that are not schema-scoped, such as data definition language (DDL) triggers and event notifications.

Example:

USE master;
GO
SELECT OBJECTPROPERTY(OBJECT_ID(N'AdventureWorks2012.HumanResources.vEmployee'), 'IsView');
GO

Example:

USE AdventureWorks2012;
GO
IF OBJECTPROPERTY (OBJECT_ID(N'Production.UnitMeasure'),'ISTABLE') = 1
   PRINT 'UnitMeasure is a table.'
ELSE IF OBJECTPROPERTY (OBJECT_ID(N'Production.UnitMeasure'),'ISTABLE') = 0
   PRINT 'UnitMeasure is not a table.'
ELSE IF OBJECTPROPERTY (OBJECT_ID(N'Production.UnitMeasure'),'ISTABLE') IS NULL
   PRINT 'ERROR: UnitMeasure is not a valid object.';
GO

Example:

USE AdventureWorks2012;
GO
SELECT OBJECTPROPERTY(OBJECT_ID('dbo.ufnGetProductDealerPrice'), 'IsDeterministic');
GO

Example:

-- Uses AdventureWorks

SELECT name, object_id, type_desc
FROM sys.objects
WHERE OBJECTPROPERTY(object_id, N'SchemaId') = SCHEMA_ID(N'dbo')
ORDER BY type_desc, name;
GO

Example:

-- Uses AdventureWorks

IF OBJECTPROPERTY (OBJECT_ID(N'dbo.DimReseller'),'ISTABLE') = 1
   SELECT 'DimReseller is a table.'
ELSE
   SELECT 'DimReseller is not a table.';
GO

__rowCount :: SExp #

Origin documentation for __rowCount

Syntax:

@@ROWCOUNT

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG .

Example:

USE AdventureWorks2012;
GO
UPDATE HumanResources.Employee
SET JobTitle = N'Executive'
WHERE NationalIDNumber = 123456789
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
GO

ceiling #

Arguments

:: SExp

numericExpression

-> SExp 

Origin documentation for ceiling

Syntax:

CEILING ( numeric_expression )

This function returns the smallest integer greater than, or equal to, the specified numeric expression.

Example:

SELECT CEILING($123.45), CEILING($-123.45), CEILING($0.0);
GO

__connections :: SExp #

Origin documentation for __connections

Syntax:

@@CONNECTIONS

This function returns the number of attempted connections - both successful and unsuccessful - since SQL Server was last started.

Example:

SELECT GETDATE() AS 'Today''s Date and Time',
@@CONNECTIONS AS 'Login Attempts';

tryParse_USING #

Arguments

:: SExp 
-> SExp 
-> SExp

culture

-> SExp 

Origin documentation for tryParse_USING

Syntax:

TRY_PARSE ( string_value AS data_type [ USING culture ] )

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.

Example:

SELECT TRY_PARSE('Jabberwokkie' AS datetime2 USING 'en-US') AS Result;

Example:

SELECT
    CASE WHEN TRY_PARSE('Aragorn' AS decimal USING 'sr-Latn-CS') IS NULL
        THEN 'True'
        ELSE 'False'
END
AS Result;

Example:

SET LANGUAGE English;
SELECT IIF(TRY_PARSE('01/01/2011' AS datetime2) IS NULL, 'True', 'False') AS Result;

tryParse #

Arguments

:: SExp 
-> SExp

dataType

-> SExp 

Origin documentation for tryParse

Syntax:

TRY_PARSE ( string_value AS data_type [ USING culture ] )

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.

Example:

SELECT TRY_PARSE('Jabberwokkie' AS datetime2 USING 'en-US') AS Result;

Example:

SELECT
    CASE WHEN TRY_PARSE('Aragorn' AS decimal USING 'sr-Latn-CS') IS NULL
        THEN 'True'
        ELSE 'False'
END
AS Result;

Example:

SET LANGUAGE English;
SELECT IIF(TRY_PARSE('01/01/2011' AS datetime2) IS NULL, 'True', 'False') AS Result;

__tranCount :: SExp #

Origin documentation for __tranCount

Syntax:

@@TRANCOUNT

Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.

Example:

PRINT @@TRANCOUNT
--  The BEGIN TRAN statement will increment the
--  transaction count by 1.
BEGIN TRAN
    PRINT @@TRANCOUNT
    BEGIN TRAN
        PRINT @@TRANCOUNT
--  The COMMIT statement will decrement the transaction count by 1.
    COMMIT
    PRINT @@TRANCOUNT
COMMIT
PRINT @@TRANCOUNT
--Results
--0
--1
--2
--1
--0

Example:

PRINT @@TRANCOUNT
--  The BEGIN TRAN statement will increment the
--  transaction count by 1.
BEGIN TRAN
    PRINT @@TRANCOUNT
    BEGIN TRAN
        PRINT @@TRANCOUNT
--  The ROLLBACK statement will clear the @@TRANCOUNT variable
--  to 0 because all active transactions will be rolled back.
ROLLBACK
PRINT @@TRANCOUNT
--Results
--0
--1
--2
--0

fileGroupId #

Arguments

:: SExp

filegroupName'

-> SExp 

Origin documentation for fileGroupId

Syntax:

FILEGROUP_ID ( 'filegroup_name' )

This function returns the filegroup identification (ID) number for a specified filegroup name.

Example:

SELECT FILEGROUP_ID('PRIMARY') AS [Filegroup ID];
GO

encryptByCert #

Arguments

:: SExp 
-> SExp

cleartext

-> SExp 

Origin documentation for encryptByCert

Syntax:

EncryptByCert ( certificate_ID , { 'cleartext' | @cleartext } )

Encrypts data with the public key of a certificate.

Example:

INSERT INTO [AdventureWorks2012].[ProtectedData04]
    VALUES ( N'Data encrypted by certificate ''Shipping04''',
    EncryptByCert(Cert_ID('JanainaCert02'), @cleartext) );
GO

currentUser :: SExp #

Origin documentation for currentUser

Syntax:

CURRENT_USER

This function returns the name of the current user. This function is equivalent to USER_NAME() .

Example:

SELECT CURRENT_USER;
GO

Example:

USE AdventureWorks2012;
GO
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
      WHERE TABLE_NAME = 'orders22')
   DROP TABLE orders22;
GO
SET NOCOUNT ON;
CREATE TABLE orders22
(
order_id int IDENTITY(1000, 1) NOT NULL,
cust_id  int NOT NULL,
order_date smalldatetime NOT NULL DEFAULT GETDATE(),
order_amt money NOT NULL,
order_person char(30) NOT NULL DEFAULT CURRENT_USER
);
GO

Example:

INSERT orders22 (cust_id, order_amt)
VALUES (5105, 577.95);
GO
SET NOCOUNT OFF;
GO

Example:

SELECT * FROM orders22;
GO

Example:

SELECT CURRENT_USER;
GO
EXECUTE AS USER = 'Arnalfo';
GO
SELECT CURRENT_USER;
GO
REVERT;
GO
SELECT CURRENT_USER;
GO

graphIdFromNodeId #

Arguments

:: SExp

nodeId

-> SExp 

Origin documentation for graphIdFromNodeId

Syntax:

GRAPH_ID_FROM_NODE_ID ( node_id )

Returns the internal graph ID for a given node ID.

Example:

SELECT GRAPH_ID_FROM_NODE_ID($node_id)
FROM Person;

indexProperty #

Arguments

:: SExp 
-> SExp 
-> SExp

property

-> SExp 

Origin documentation for indexProperty

Syntax:

INDEXPROPERTY ( object_ID , index_or_statistics_name , property )

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.

Example:

SELECT
    INDEXPROPERTY(OBJECT_ID('HumanResources.Employee'),
        'PK_Employee_BusinessEntityID','IsClustered')AS [Is Clustered],
    INDEXPROPERTY(OBJECT_ID('HumanResources.Employee'),
        'PK_Employee_BusinessEntityID','IndexDepth') AS [Index Depth],
    INDEXPROPERTY(OBJECT_ID('HumanResources.Employee'),
        'PK_Employee_BusinessEntityID','IndexFillFactor') AS [Fill Factor];

Example:

-- Uses AdventureWorks

SELECT
INDEXPROPERTY(OBJECT_ID('dbo.FactResellerSales'),
    'ClusteredIndex_6d10fa223e5e4c1fbba087e29e16a7a2','IsClustered') AS [Is Clustered],
INDEXPROPERTY(OBJECT_ID('dbo.FactResellerSales'),
    'ClusteredIndex_6d10fa223e5e4c1fbba087e29e16a7a2','IsColumnstore') AS [Is Columnstore Index],
INDEXPROPERTY(OBJECT_ID('dbo.FactResellerSales'),
    'ClusteredIndex_6d10fa223e5e4c1fbba087e29e16a7a2','IndexFillFactor') AS [Fill Factor];
GO

__packetErrors :: SExp #

Origin documentation for __packetErrors

Syntax:

@@PACKET_ERRORS

Returns the number of network packet errors that have occurred on SQL Server connections since SQL Server was last started.

Example:

SELECT @@PACKET_ERRORS AS 'Packet Errors';

__totalWrite :: SExp #

Origin documentation for __totalWrite

Syntax:

@@TOTAL_WRITE

Returns the number of disk writes by SQL Server since SQL Server was last started.

Example:

SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of'

__maxPrecision :: SExp #

Origin documentation for __maxPrecision

Syntax:

@@MAX_PRECISION

Returns the precision level used by decimal and numeric data types as currently set in the server.

Example:

SELECT @@MAX_PRECISION AS 'Max Precision'

nChar #

Arguments

:: SExp

integerExpression

-> SExp 

Origin documentation for nChar

Syntax:

NCHAR ( integer_expression )

Returns the Unicode character with the specified integer code, as defined by the Unicode standard.

Example:

CREATE DATABASE test COLLATE Finnish_Swedish_100_CS_AS_SC;
DECLARE @d NVARCHAR(10) = N'𣅿';
-- Old style method.
SELECT NCHAR(0xD84C) + NCHAR(0xDD7F);

-- Preferred method.
SELECT NCHAR(143743);

-- Alternative preferred method.
SELECT NCHAR(UNICODE(@d));

Example:

DECLARE @nstring NCHAR(8);
SET @nstring = N'København';
SELECT UNICODE(SUBSTRING(@nstring, 2, 1)),
   NCHAR(UNICODE(SUBSTRING(@nstring, 2, 1)));
GO

Example:

-- The @position variable holds the position of the character currently
-- being processed. The @nstring variable is the Unicode character
-- string to process.
DECLARE @position INT, @nstring NCHAR(9);
-- Initialize the current position variable to the first character in
-- the string.
SET @position = 1;
-- Initialize the character string variable to the string to process.
-- Notice that there is an N before the start of the string. This
-- indicates that the data following the N is Unicode data.
SET @nstring = N'København';
-- Print the character number of the position of the string you are at,
-- the actual Unicode character you are processing, and the UNICODE
-- value for this particular character.
PRINT 'Character #' + ' ' + 'Unicode Character' + ' ' + 'UNICODE Value';
WHILE @position <= DATALENGTH(@nstring)
   BEGIN
   SELECT @position,
      NCHAR(UNICODE(SUBSTRING(@nstring, @position, 1))),
      CONVERT(NCHAR(17), SUBSTRING(@nstring, @position, 1)),
      UNICODE(SUBSTRING(@nstring, @position, 1))
   SELECT @position = @position + 1
   END;
GO

fileIdex #

Arguments

:: SExp

fileName'

-> SExp 

Origin documentation for fileIdex

Syntax:

FILE_IDEX ( file_name )

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.

Example:

USE AdventureWorks2012;
GO
SELECT FILE_IDEX('AdventureWorks2012_Data') AS 'File ID';
GO

Example:

USE AdventureWorks2012;
GO
SELECT FILE_IDEX((SELECT TOP (1) name FROM sys.database_files WHERE type = 1)) AS 'File ID';
GO

Example:

SELECT FILE_IDEX((SELECT name FROM sys.master_files WHERE type = 4))
AS 'File_ID';

user :: SExp #

Origin documentation for user

Syntax:

USER

Allows a system-supplied value for the database user name of the current user to be inserted into a table when no default value is specified.

Example:

DECLARE @usr CHAR(30)
SET @usr = user
SELECT 'The current user''s database username is: '+ @usr
GO

Example:

USE AdventureWorks2012;
GO
CREATE TABLE inventory22
(
 part_id INT IDENTITY(100, 1) NOT NULL,
 description VARCHAR(30) NOT NULL,
 entry_person VARCHAR(30) NOT NULL DEFAULT USER
)
GO
INSERT inventory22 (description)
VALUES ('Red pencil')
INSERT inventory22 (description)
VALUES ('Blue pencil')
INSERT inventory22 (description)
VALUES ('Green pencil')
INSERT inventory22 (description)
VALUES ('Black pencil')
INSERT inventory22 (description)
VALUES ('Yellow pencil')
GO

Example:

SELECT * FROM inventory22 ORDER BY part_id;
GO

Example:

SELECT USER;
GO
EXECUTE AS USER = 'Mario';
GO
SELECT USER;
GO
REVERT;
GO
SELECT USER;
GO

assemblyProperty #

Arguments

:: SExp 
-> SExp

propertyName

-> SExp 

Origin documentation for assemblyProperty

Syntax:

ASSEMBLYPROPERTY('assembly_name', 'property_name')

This function returns information about a property of an assembly.

Example:

USE AdventureWorks2012;
GO
SELECT ASSEMBLYPROPERTY ('HelloWorld' , 'PublicKey');

substring #

Arguments

:: SExp 
-> SExp 
-> SExp

length'

-> SExp 

Origin documentation for substring

Syntax:

SUBSTRING ( expression ,start , length )

Returns part of a character, binary, text, or image expression in SQL Server.

Example:

SELECT name, SUBSTRING(name, 1, 1) AS Initial ,
SUBSTRING(name, 3, 2) AS ThirdAndFourthCharacters
FROM sys.databases
WHERE database_id < 5;

Example:

SELECT x = SUBSTRING('abcdef', 2, 3);

Example:

USE pubs;
SELECT pub_id, SUBSTRING(logo, 1, 10) AS logo,
   SUBSTRING(pr_info, 1, 10) AS pr_info
FROM pub_info
WHERE pub_id = '1756';

Example:

IF EXISTS (SELECT table_name FROM INFORMATION_SCHEMA.TABLES
      WHERE table_name = 'npub_info')
   DROP TABLE npub_info;
GO
-- Create npub_info table in pubs database. Borrowed from instpubs.sql.
USE pubs;
GO
CREATE TABLE npub_info
(
 pub_id CHAR(4) NOT NULL
    REFERENCES publishers(pub_id)
    CONSTRAINT UPKCL_npubinfo PRIMARY KEY CLUSTERED,
pr_info ntext NULL
);

GO

-- Fill the pr_info column in npub_info with international data.
RAISERROR('Now at the inserts to pub_info...',0,1);

GO

INSERT npub_info VALUES('0736', N'üThis is sample text data for New Moon Books, publisher 0736 in the pubs database')
,('0877', N'üThis is sample text data for Binnet & Hardley, publisher 0877 in the pubs databa')
,('1389', N'üThis is sample text data for Algodata Infosystems, publisher 1389 in the pubs da')
,('9952', N'üThis is sample text data for Scootney Books, publisher 9952 in the pubs database')
,('1622', N'üThis is sample text data for Five Lakes Publishing, publisher 1622 in the pubs d')
,('1756', N'üThis is sample text data for Ramona Publishers, publisher 1756 in the pubs datab')
,('9901', N'üThis is sample text data for GGG&G, publisher 9901 in the pubs database. GGG&G i')
,('9999', N'üThis is sample text data for Lucerne Publishing, publisher 9999 in the pubs data');
GO
-- Join between npub_info and pub_info on pub_id.
SELECT pr.pub_id, SUBSTRING(pr.pr_info, 1, 35) AS pr_info,
   SUBSTRING(npr.pr_info, 1, 35) AS npr_info
FROM pub_info pr INNER JOIN npub_info npr
   ON pr.pub_id = npr.pub_id
ORDER BY pr.pub_id ASC;

Example:

-- Uses AdventureWorks

SELECT LastName, SUBSTRING(FirstName, 1, 1) AS Initial
FROM dbo.DimEmployee
WHERE LastName LIKE 'Bar%'
ORDER BY LastName;

Example:

USE ssawPDW;

SELECT TOP 1 SUBSTRING('abcdef', 2, 3) AS x FROM dbo.DimCustomer;

hostId :: SExp #

Origin documentation for hostId

Syntax:

HOST_ID ()

Returns the workstation identification number. The workstation identification number is the process ID (PID) of the application on the client computer that is connecting to SQL Server.

Example:

CREATE TABLE Orders
   (OrderID     INT       PRIMARY KEY,
    CustomerID  NCHAR(5)  REFERENCES Customers(CustomerID),
    TerminalID  CHAR(8)   NOT NULL DEFAULT HOST_ID(),
    OrderDate   DATETIME  NOT NULL,
    ShipDate    DATETIME  NULL,
    ShipperID   INT       NULL REFERENCES Shippers(ShipperID));
GO

atn2 #

Arguments

:: SExp 
-> SExp

floatExpressionr

-> SExp 

Origin documentation for atn2

Syntax:

ATN2 ( float_expression , float_expression )

Returns the angle, in radians, between the positive x-axis and the ray from the origin to the point (y, x), where x and y are the values of the two specified float expressions.

Example:

DECLARE @x FLOAT = 35.175643, @y FLOAT = 129.44;
SELECT 'The ATN2 of the angle is: ' + CONVERT(VARCHAR, ATN2(@y, @x));
GO

colName #

Arguments

:: SExp 
-> SExp

columnId

-> SExp 

Origin documentation for colName

Syntax:

COL_NAME ( table_id , column_id )

This function returns the name of a table column, based on the table identification number and column identification number values of that table column.

Example:

-- Uses AdventureWorks

SELECT COL_NAME(OBJECT_ID('dbo.FactResellerSales'), 1) AS FirstColumnName,
COL_NAME(OBJECT_ID('dbo.FactResellerSales'), 2) AS SecondColumnName;

newsequentialid :: SExp #

Origin documentation for newsequentialid

Syntax:

NEWSEQUENTIALID ( )

Creates a GUID that is greater than any GUID previously generated by this function on a specified computer since Windows was started. After restarting Windows, the GUID can start again from a lower range, but is still globally unique. When a GUID column is used as a row identifier, using NEWSEQUENTIALID can be faster than using the NEWID function. This is because the NEWID function causes random activity and uses fewer cached data pages. Using NEWSEQUENTIALID also helps to completely fill the data and index pages.

Important

If privacy is a concern, do not use this function. It is possible to guess the value of the next generated GUID and, therefore, access data associated with that GUID.

NEWSEQUENTIALID is a wrapper over the Windows UuidCreateSequential function, with some byte shuffling applied .

Warning

The UuidCreateSequential function has hardware dependencies. On SQL Server, clusters of sequential values can develop when databases (such as contained databases) are moved to other computers. When using Always On and on SQL Database, clusters of sequential values can develop if the database fails over to a different computer.

Example:

CREATE TABLE myTable (ColumnA uniqueidentifier DEFAULT NEWSEQUENTIALID());

Example:

CREATE TABLE myTable (ColumnA uniqueidentifier DEFAULT dbo.myfunction(NEWSEQUENTIALID()));

difference #

Arguments

:: SExp 
-> SExp

characterExpressionr

-> SExp 

Origin documentation for difference

Syntax:

DIFFERENCE ( character_expression , character_expression )

This function returns an integer value measuring the difference between the SOUNDEX() values of two different character expressions.

Example:

-- Returns a DIFFERENCE value of 4, the least possible difference.
SELECT SOUNDEX('Green'), SOUNDEX('Greene'), DIFFERENCE('Green','Greene');
GO
-- Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('Blotchet-Halls'), SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene');
GO

identIncr #

Arguments

:: SExp

tableOrView

-> SExp 

Origin documentation for identIncr

Syntax:

IDENT_INCR ( 'table_or_view' )

Returns the increment value specified when creating a table or view's identity column.

Example:

USE AdventureWorks2012;
GO
SELECT IDENT_INCR('Person.Address') AS Identity_Increment;
GO

Example:

USE AdventureWorks2012;
GO
SELECT TABLE_SCHEMA, TABLE_NAME,
   IDENT_INCR(TABLE_SCHEMA + '.' + TABLE_NAME) AS IDENT_INCR
FROM INFORMATION_SCHEMA.TABLES
WHERE IDENT_INCR(TABLE_SCHEMA + '.' + TABLE_NAME) IS NOT NULL;

currentTimeStamp :: SExp #

Origin documentation for currentTimeStamp

Syntax:

CURRENT_TIMESTAMP

This function returns the current database system timestamp as a datetime value, without the database time zone offset. CURRENT_TIMESTAMP derives this value from the operating system of the computer on which the instance of SQL Server runs.

Note

SYSDATETIME and SYSUTCDATE have more precision, as measured by fractional seconds precision, than GETDATE and GETUTCDATE . The SYSDATETIMEOFFSET function includes the system time zone offset. You can assign SYSDATETIME , SYSUTCDATETIME , and SYSDATETIMEOFFSET to a variable of any of the date and time types.

This function is the ANSI SQL equivalent to GETDATE .

See Date and Time Data Types and Functions for an overview of all the Transact-SQL date and time data types and functions.

Example:

SELECT SYSDATETIME()
    ,SYSDATETIMEOFFSET()
    ,SYSUTCDATETIME()
    ,CURRENT_TIMESTAMP
    ,GETDATE()
    ,GETUTCDATE();
/* Returned:
SYSDATETIME()      2007-04-30 13:10:02.0474381
SYSDATETIMEOFFSET()2007-04-30 13:10:02.0474381 -07:00
SYSUTCDATETIME()   2007-04-30 20:10:02.0474381
CURRENT_TIMESTAMP  2007-04-30 13:10:02.047
GETDATE()          2007-04-30 13:10:02.047
GETUTCDATE()       2007-04-30 20:10:02.047
*/

Example:

SELECT CONVERT (DATE, SYSDATETIME())
    ,CONVERT (DATE, SYSDATETIMEOFFSET())
    ,CONVERT (DATE, SYSUTCDATETIME())
    ,CONVERT (DATE, CURRENT_TIMESTAMP)
    ,CONVERT (DATE, GETDATE())
    ,CONVERT (DATE, GETUTCDATE());

/* Returned
SYSDATETIME()      2007-05-03
SYSDATETIMEOFFSET()2007-05-03
SYSUTCDATETIME()   2007-05-04
CURRENT_TIMESTAMP  2007-05-03
GETDATE()          2007-05-03
GETUTCDATE()       2007-05-04
*/

Example:

SELECT CONVERT (TIME, SYSDATETIME())
    ,CONVERT (TIME, SYSDATETIMEOFFSET())
    ,CONVERT (TIME, SYSUTCDATETIME())
    ,CONVERT (TIME, CURRENT_TIMESTAMP)
    ,CONVERT (TIME, GETDATE())
    ,CONVERT (TIME, GETUTCDATE());

/* Returned
SYSDATETIME()      13:18:45.3490361
SYSDATETIMEOFFSET()13:18:45.3490361
SYSUTCDATETIME()   20:18:45.3490361
CURRENT_TIMESTAMP  13:18:45.3470000
GETDATE()          13:18:45.3470000
GETUTCDATE()       20:18:45.3470000
*/

Example:

SELECT CURRENT_TIMESTAMP;

__dbts :: SExp #

Origin documentation for __dbts

Syntax:

@@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.

Example:

USE AdventureWorks2012;
GO
SELECT @@DBTS;

typeProperty #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for typeProperty

Syntax:

TYPEPROPERTY (type , property)

Returns information about a data type.

Example:

SELECT TYPEPROPERTY(SCHEMA_NAME(schema_id) + '.' + name, 'OwnerId') AS owner_id, name, system_type_id, user_type_id, schema_id
FROM sys.types;

Example:

SELECT TYPEPROPERTY( 'tinyint', 'PRECISION');

currentTimeZoneId :: SExp #

Origin documentation for currentTimeZoneId

Syntax:

CURRENT_TIMEZONE_ID ( )

This function returns the ID of the time zone observed by a server or an instance. For Azure SQL Managed Instance, return value is based on the time zone of the instance itself assigned during instance creation, not the time zone of the underlying operating system.

Note

For SQL Database time zone is always set to UTC and CURRENT_TIMEZONE_ID returns the id of the UTC time zone.

Example:

SELECT CURRENT_TIMEZONE_ID();
/* Returned:
W. Europe Standard Time
*/

asin #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for asin

Syntax:

ASIN ( float_expression )

A function that returns the angle, in radians, whose sine is the specified float expression. This is also called arcsine .

Example:

/* The first value will be -1.01. This fails because the value is
outside the range.*/
DECLARE @angle FLOAT
SET @angle = -1.01
SELECT 'The ASIN of the angle is: ' + CONVERT(VARCHAR, ASIN(@angle))
GO

-- The next value is -1.00.
DECLARE @angle FLOAT
SET @angle = -1.00
SELECT 'The ASIN of the angle is: ' + CONVERT(VARCHAR, ASIN(@angle))
GO

-- The next value is 0.1472738.
DECLARE @angle FLOAT
SET @angle = 0.1472738
SELECT 'The ASIN of the angle is: ' + CONVERT(VARCHAR, ASIN(@angle))
GO

Example:

SELECT ASIN(1.00) AS asinCalc;

Example:

SELECT ASIN(1.1472738) AS asinCalc;

hasDbaccess #

Arguments

:: SExp

databaseName

-> SExp 

Origin documentation for hasDbaccess

Syntax:

HAS_DBACCESS ( 'database_name' )

Returns information about whether the user has access to the specified database.

Example:

SELECT HAS_DBACCESS('AdventureWorks2012');
GO

Example:

SELECT HAS_DBACCESS('AdventureWorksPDW2012');
GO

applockMode #

Arguments

:: SExp 
-> SExp 
-> SExp

lockOwner

-> SExp 

Origin documentation for applockMode

Syntax:

APPLOCK_MODE( 'database_principal' , 'resource_name' , 'lock_owner' )

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.

Example:

USE AdventureWorks2012;
GO
BEGIN TRAN;
DECLARE @result INT;
EXEC @result=sp_getapplock
    @DbPrincipal='public',
    @Resource='Form1',
    @LockMode='Shared',
    @LockOwner='Transaction';
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
GO

Example:

Use AdventureWorks2012;
GO
BEGIN TRAN;
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
--Result set: NoLock

SELECT APPLOCK_TEST('public', 'Form1', 'Shared', 'Transaction');
--Result set: 1 (Lock is grantable.)

SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: 0 (Lock is not grantable.)
GO

Example:

EXEC sp_releaseapplock @Resource='Form1', @DbPrincipal='public';
GO

Example:

SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: '1' (The lock is grantable.)
GO

Example:

COMMIT TRAN;
GO

fileName #

Arguments

:: SExp

fileId'

-> SExp 

Origin documentation for fileName

Syntax:

FILE_NAME ( file_id )

This function returns the logical file name for a given file identification (ID) number.

Example:

SELECT FILE_NAME(1) AS 'File Name 1', FILE_NAME(2) AS 'File Name 2';
GO

square #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for square

Syntax:

SQUARE ( float_expression )

Returns the square of the specified float value.

Example:

DECLARE @h FLOAT, @r FLOAT;
SET @h = 5;
SET @r = 1;
SELECT PI()* SQUARE(@r)* @h AS 'Cyl Vol';

Example:

-- Uses AdventureWorks

CREATE TABLE Containers (
    ID INT NOT NULL,
    Name VARCHAR(20),
    Volume FLOAT(24));

INSERT INTO Containers VALUES (1, 'Cylinder', '125.22');
INSERT INTO Containers VALUES (2, 'Cube', '23.98');

SELECT Name, SQUARE(Volume) AS VolSquared
FROM Containers;

atan #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for atan

Syntax:

ATAN ( float_expression )

A function that returns the angle, in radians, whose tangent is a specified float expression. This is also called arctangent.

Example:

SELECT 'The ATAN of -45.01 is: ' + CONVERT(varchar, ATAN(-45.01))
SELECT 'The ATAN of -181.01 is: ' + CONVERT(varchar, ATAN(-181.01))
SELECT 'The ATAN of 0 is: ' + CONVERT(varchar, ATAN(0))
SELECT 'The ATAN of 0.1472738 is: ' + CONVERT(varchar, ATAN(0.1472738))
SELECT 'The ATAN of 197.1099392 is: ' + CONVERT(varchar, ATAN(197.1099392))
GO

Example:

SELECT ATAN(45.87) AS atanCalc1,
    ATAN(-181.01) AS atanCalc2,
    ATAN(0) AS atanCalc3,
    ATAN(0.1472738) AS atanCalc4,
    ATAN(197.1099392) AS atanCalc5;

objectDefinition #

Arguments

:: SExp

objectId'

-> SExp 

Origin documentation for objectDefinition

Syntax:

OBJECT_DEFINITION ( object_id )

Returns the Transact-SQL source text of the definition of a specified object.

Example:

USE AdventureWorks2012;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID(N'Person.uAddress')) AS [Trigger Definition];
GO

Example:

USE AdventureWorks2012;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID(N'sys.sp_columns')) AS [Object Definition];
GO

exp #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for exp

Syntax:

EXP ( float_expression )

Returns the exponential value of the specified float expression.

Example:

DECLARE @var FLOAT
SET @var = 10
SELECT 'The EXP of the variable is: ' + CONVERT(VARCHAR, EXP(@var))
GO

Example:

SELECT EXP(LOG(20)), LOG(EXP(20))
GO

Example:

SELECT EXP(10);

Example:

SELECT EXP( LOG(20)), LOG( EXP(20));

replicate #

Arguments

:: SExp 
-> SExp

integerExpression

-> SExp 

Origin documentation for replicate

Syntax:

REPLICATE ( string_expression , integer_expression )

Repeats a string value a specified number of times.

Example:

SELECT [Name]
, REPLICATE('0', 4) + [ProductLine] AS 'Line Code'
FROM [Production].[Product]
WHERE [ProductLine] = 'T'
ORDER BY [Name];
GO

Example:

IF EXISTS(SELECT name FROM sys.tables
      WHERE name = 't1')
   DROP TABLE t1;
GO
CREATE TABLE t1
(
 c1 varchar(3),
 c2 char(3)
);
GO
INSERT INTO t1 VALUES ('2', '2'), ('37', '37'),('597', '597');
GO
SELECT REPLICATE('0', 3 - DATALENGTH(c1)) + c1 AS 'Varchar Column',
       REPLICATE('0', 3 - DATALENGTH(c2)) + c2 AS 'Char Column'
FROM t1;
GO

Example:

-- Uses AdventureWorks

SELECT EnglishProductName AS Name,
   ProductAlternateKey AS ItemCode,
   REPLICATE('0', 4) + ProductAlternateKey AS FullItemCode
FROM dbo.DimProduct
ORDER BY Name;

edgeIdFromParts #

Arguments

:: SExp 
-> SExp

graphId

-> SExp 

Origin documentation for edgeIdFromParts

Syntax:

EDGE_ID_FROM_PARTS ( object_id, graph_id )

Returns the character representation (JSON) of the edge ID for a given object ID and graph ID.

Example:

INSERT INTO likes($edge_id, $from_id, $to_id, rating)
SELECT EDGE_ID_FROM_PARTS(OBJECT_ID('likes'), dataset_key) as from_id
, NODE_ID_FROM_PARTS(OBJECT_ID('Person'), ID) as from_id
, NODE_ID_FROM_PARTS(OBJECT_ID('Restaurant'), ID) as to_id
, rating
FROM OPENROWSET (BULK 'person_likes_restaurant.csv',
    DATA_SOURCE = 'staging_data_source',
    FORMATFILE = 'format-files/likes.xml',
    FORMATFILE_DATA_SOURCE = 'format_files_source',
    FIRSTROW = 2) AS staging_data;
;

len #

Arguments

:: SExp

stringExpression

-> SExp 

Origin documentation for len

Syntax:

LEN ( string_expression )

Returns the number of characters of the specified string expression, excluding trailing spaces.

Note

To return the number of bytes used to represent an expression, use the DATALENGTH function.

Example:

  DECLARE @v1 VARCHAR(40),
    @v2 NVARCHAR(40);
SELECT
@v1 = 'Test of 22 characters ',
@v2 = 'Test of 22 characters ';
SELECT LEN(@v1) AS [VARCHAR LEN] , DATALENGTH(@v1) AS [VARCHAR DATALENGTH];
SELECT LEN(@v2) AS [NVARCHAR LEN], DATALENGTH(@v2) AS [NVARCHAR DATALENGTH];

Example:

SELECT LEN(FirstName) AS Length, FirstName, LastName
FROM Sales.vIndividualCustomer
WHERE CountryRegionName = 'Australia';
GO

Example:

USE AdventureWorks2016
GO
SELECT DISTINCT LEN(FirstName) AS FNameLength, FirstName, LastName
FROM dbo.DimEmployee AS e
INNER JOIN dbo.DimGeography AS g
    ON e.SalesTerritoryKey = g.SalesTerritoryKey
WHERE EnglishCountryRegionName = 'Australia';

typeName #

Arguments

:: SExp

typeId'

-> SExp 

Origin documentation for typeName

Syntax:

TYPE_NAME ( type_id )

Returns the unqualified type name of a specified type ID.

Example:

SELECT o.name AS obj_name, c.name AS col_name,
       TYPE_NAME(c.user_type_id) AS type_name
FROM sys.objects AS o
JOIN sys.columns AS c  ON o.object_id = c.object_id
WHERE o.name = 'Vendor'
ORDER BY col_name;
GO

Example:

SELECT TYPE_NAME(36) AS Type36, TYPE_NAME(239) AS Type239;
GO

Example:

SELECT * FROM sys.types;
GO

parseName #

Arguments

:: SExp 
-> SExp

objectPiece

-> SExp 

Origin documentation for parseName

Syntax:

PARSENAME ('object_name' , object_piece )

Returns the specified part of an object name. The parts of an object that can be retrieved are the object name, schema name, database name, and server name.

Note

The PARSENAME function does not indicate whether an object by the specified name exists. PARSENAME just returns the specified part of the specified object name.

Example:

-- Uses AdventureWorks

SELECT PARSENAME('AdventureWorksPDW2012.dbo.DimCustomer', 1) AS 'Object Name';
SELECT PARSENAME('AdventureWorksPDW2012.dbo.DimCustomer', 2) AS 'Schema Name';
SELECT PARSENAME('AdventureWorksPDW2012.dbo.DimCustomer', 3) AS 'Database Name';
SELECT PARSENAME('AdventureWorksPDW2012.dbo.DimCustomer', 4) AS 'Server Name';
GO

graphIdFromEdgeId #

Arguments

:: SExp

edgeId

-> SExp 

Origin documentation for graphIdFromEdgeId

Syntax:

GRAPH_ID_FROM_EDGE_ID ( edge_id )

Returns the internal graph ID for a given edge ID.

Example:

SELECT GRAPH_ID_FROM_EDGE_ID($edge_id)
FROM friendOf;

verifySignedByCert #

Arguments

:: SExp 
-> SExp 
-> SExp

signature

-> SExp 

Origin documentation for verifySignedByCert

Syntax:

VerifySignedByCert( Cert_ID , signed_data , signature )

Tests whether digitally signed data has been changed since it was signed.

Example:

SELECT Data, VerifySignedByCert( Cert_Id( 'Shipping04' ),
    Signed_Data, DataSignature ) AS IsSignatureValid
FROM [AdventureWorks2012].[SignedData04]
WHERE Description = N'data signed by certificate ''Shipping04''';
GO

Example:

SELECT Data FROM [AdventureWorks2012].[SignedData04]
WHERE VerifySignedByCert( Cert_Id( 'Shipping04' ), Data,
    DataSignature ) = 1
AND Description = N'data signed by certificate ''Shipping04''';
GO

applockTest #

Arguments

:: SExp 
-> SExp 
-> SExp 
-> SExp

lockOwner

-> SExp 

Origin documentation for applockTest

Syntax:

APPLOCK_TEST ( 'database_principal' , 'resource_name' , 'lock_mode' , 'lock_owner' )

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.

Example:

USE AdventureWorks2012;
GO
BEGIN TRAN;
DECLARE @result INT;
EXEC @result=sp_getapplock
    @DbPrincipal='public',
    @Resource='Form1',
    @LockMode='Shared',
    @LockOwner='Transaction';
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
GO

Example:

Use AdventureWorks2012;
GO
BEGIN TRAN;
SELECT APPLOCK_MODE('public', 'Form1', 'Transaction');
--Result set: NoLock

SELECT APPLOCK_TEST('public', 'Form1', 'Shared', 'Transaction');
--Result set: 1 (Lock is grantable.)

SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: 0 (Lock is not grantable.)
GO

Example:

EXEC sp_releaseapplock @Resource='Form1', @DbPrincipal='public';
GO

Example:

SELECT APPLOCK_TEST('public', 'Form1', 'Exclusive', 'Transaction');
--Result set: '1' (The lock is grantable.)
GO

Example:

COMMIT TRAN;
GO

rowNumber_PARTITION_BY #

Arguments

:: NonEmpty SExp 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for rowNumber_PARTITION_BY

Syntax:

ROW_NUMBER ( )
    OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )

Numbers the output of a result set. More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK provides the same numeric value for ties (for example 1, 2, 2, 4, 5).

Note

ROW_NUMBER is a temporary value calculated when the query is run. To persist numbers in a table, see IDENTITY Property and SEQUENCE .

Example:

SELECT
  name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5
ORDER BY name ASC;

Example:

SELECT
  ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#,
  name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5;

Example:

SELECT
  ROW_NUMBER() OVER(PARTITION BY recovery_model_desc ORDER BY name ASC)
    AS Row#,
  name, recovery_model_desc
FROM sys.databases WHERE database_id < 5;

Example:

USE AdventureWorks2012;
GO
SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row,
    FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD"
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;

Example:

USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
    FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;

Example:

USE AdventureWorks2012;
GO
SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2,1) AS SalesYTD,
ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC)
  AS Row
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0
ORDER BY TerritoryName;

Example:

-- Uses AdventureWorks

SELECT ROW_NUMBER() OVER(ORDER BY SUM(SalesAmountQuota) DESC)
    AS RowNumber,
    FirstName, LastName,
    CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName;

Example:

-- Uses AdventureWorks

SELECT ROW_NUMBER() OVER(PARTITION BY SalesTerritoryKey
        ORDER BY SUM(SalesAmountQuota) DESC) AS RowNumber,
    LastName, SalesTerritoryKey AS Territory,
    CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName, SalesTerritoryKey;

rowNumber #

Arguments

:: OverOrderBy

overorderby

-> SExp 

Origin documentation for rowNumber

Syntax:

ROW_NUMBER ( )
    OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )

Numbers the output of a result set. More specifically, returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows sequentially (for example 1, 2, 3, 4, 5). RANK provides the same numeric value for ties (for example 1, 2, 2, 4, 5).

Note

ROW_NUMBER is a temporary value calculated when the query is run. To persist numbers in a table, see IDENTITY Property and SEQUENCE .

Example:

SELECT
  name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5
ORDER BY name ASC;

Example:

SELECT
  ROW_NUMBER() OVER(ORDER BY name ASC) AS Row#,
  name, recovery_model_desc
FROM sys.databases
WHERE database_id < 5;

Example:

SELECT
  ROW_NUMBER() OVER(PARTITION BY recovery_model_desc ORDER BY name ASC)
    AS Row#,
  name, recovery_model_desc
FROM sys.databases WHERE database_id < 5;

Example:

USE AdventureWorks2012;
GO
SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row,
    FirstName, LastName, ROUND(SalesYTD,2,1) AS "Sales YTD"
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;

Example:

USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
    FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;

Example:

USE AdventureWorks2012;
GO
SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2,1) AS SalesYTD,
ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC)
  AS Row
FROM Sales.vSalesPerson
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0
ORDER BY TerritoryName;

Example:

-- Uses AdventureWorks

SELECT ROW_NUMBER() OVER(ORDER BY SUM(SalesAmountQuota) DESC)
    AS RowNumber,
    FirstName, LastName,
    CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName;

Example:

-- Uses AdventureWorks

SELECT ROW_NUMBER() OVER(PARTITION BY SalesTerritoryKey
        ORDER BY SUM(SalesAmountQuota) DESC) AS RowNumber,
    LastName, SalesTerritoryKey AS Territory,
    CONVERT(varchar(13), SUM(SalesAmountQuota),1) AS SalesQuota
FROM dbo.DimEmployee AS e
INNER JOIN dbo.FactSalesQuota AS sq
    ON e.EmployeeKey = sq.EmployeeKey
WHERE e.SalesPersonFlag = 1
GROUP BY LastName, FirstName, SalesTerritoryKey;

__serverName :: SExp #

Origin documentation for __serverName

Syntax:

@@SERVERNAME

No description

Example:

SELECT @@SERVERNAME AS 'Server Name'

__language :: SExp #

Origin documentation for __language

Syntax:

@@LANGUAGE

Returns the name of the language currently being used.

Example:

SELECT @@LANGUAGE AS 'Language Name';

stringEscape #

Arguments

:: SExp 
-> SExp

type'

-> SExp 

Origin documentation for stringEscape

Syntax:

STRING_ESCAPE( text , type )

Escapes special characters in texts and returns text with escaped characters. STRING_ESCAPE is a deterministic function, introduced in SQL Server 2016.

Example:

SELECT STRING_ESCAPE('\   /
\\    "     ', 'json') AS escapedText;

cos #

Arguments

:: SExp

floatExpression

-> SExp 

Origin documentation for cos

Syntax:

COS ( float_expression )

A mathematical function that returns the trigonometric cosine of the specified angle - measured in radians - in the specified expression.

Example:

  DECLARE @angle FLOAT;
SET @angle = 14.78;
SELECT 'The COS of the angle is: ' + CONVERT(VARCHAR,COS(@angle));
GO

Example:

SELECT COS(14.76) AS cosCalc1, COS(-0.1472738) AS cosCalc2;

pi :: SExp #

Origin documentation for pi

Syntax:

PI ( )

Returns the constant value of PI.

Example:

SELECT PI();
GO

day #

Arguments

:: SExp

date

-> SExp 

Origin documentation for day

Syntax:

DAY ( date )

This function returns an integer that represents the day (day of the month) of the specified date .

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SELECT DAY('2015-04-30 01:01:01.1234567');

Example:

SELECT YEAR(0), MONTH(0), DAY(0);

datediffBig #

Arguments

:: SExp 
-> SExp 
-> SExp

enddate

-> SExp 

Origin documentation for datediffBig

Syntax:

DATEDIFF_BIG ( datepart , startdate , enddate )

This function returns the count (as a signed big integer value) of the specified datepart boundaries crossed between the specified startdate and enddate .

See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SELECT DATEDIFF_BIG(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF_BIG(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Example:

CREATE TABLE dbo.Duration
    (startDate datetime2, endDate datetime2);

INSERT INTO dbo.Duration(startDate,endDate)
    VALUES('2007-05-06 12:10:09', '2007-05-07 12:10:09');

SELECT DATEDIFF_BIG(day, startDate, endDate) AS 'Duration'
    FROM dbo.Duration;
-- Returns: 1

Example:

DECLARE @date1 DATETIME2, @date2 DATETIME2, @result VARCHAR(100)
DECLARE @years BIGINT, @months BIGINT, @days BIGINT, @hours BIGINT, @minutes BIGINT, @seconds BIGINT, @milliseconds BIGINT

SET @date1 = '0001-01-01 00:00:00.00000000'
SET @date2 = '2018-12-12 07:08:01.12345678'

SELECT @years = DATEDIFF(yy, @date1, @date2)
IF DATEADD(yy, -@years, @date2) < @date1
SELECT @years = @years-1
SET @date2 = DATEADD(yy, -@years, @date2)

SELECT @months = DATEDIFF(mm, @date1, @date2)
IF DATEADD(mm, -@months, @date2) < @date1
SELECT @months=@months-1
SET @date2= DATEADD(mm, -@months, @date2)

SELECT @days=DATEDIFF(dd, @date1, @date2)
IF DATEADD(dd, -@days, @date2) < @date1
SELECT @days=@days-1
SET @date2= DATEADD(dd, -@days, @date2)

SELECT @hours=DATEDIFF(hh, @date1, @date2)
IF DATEADD(hh, -@hours, @date2) < @date1
SELECT @hours=@hours-1
SET @date2= DATEADD(hh, -@hours, @date2)

SELECT @minutes=DATEDIFF(mi, @date1, @date2)
IF DATEADD(mi, -@minutes, @date2) < @date1
SELECT @minutes=@minutes-1
SET @date2= DATEADD(mi, -@minutes, @date2)

SELECT @seconds=DATEDIFF(s, @date1, @date2)
IF DATEADD(s, -@seconds, @date2) < @date1
SELECT @seconds=@seconds-1
SET @date2= DATEADD(s, -@seconds, @date2)

SELECT @milliseconds=DATEDIFF(ms, @date1, @date2)

SELECT @result= ISNULL(CAST(NULLIF(@years,0) AS VARCHAR(10)) + ' years,','')
     + ISNULL(' ' + CAST(NULLIF(@months,0) AS VARCHAR(10)) + ' months,','')
     + ISNULL(' ' + CAST(NULLIF(@days,0) AS VARCHAR(10)) + ' days,','')
     + ISNULL(' ' + CAST(NULLIF(@hours,0) AS VARCHAR(10)) + ' hours,','')
     + ISNULL(' ' + CAST(@minutes AS VARCHAR(10)) + ' minutes and','')
     + ISNULL(' ' + CAST(@seconds AS VARCHAR(10))
          + CASE WHEN @milliseconds > 0 THEN '.' + CAST(@milliseconds AS VARCHAR(10))
               ELSE '' END
          + ' seconds','')

SELECT @result

__ioBusy :: SExp #

Origin documentation for __ioBusy

Syntax:

@@IO_BUSY

Returns the time that SQL Server has spent performing input and output operations since SQL Server was last started. The result is in CPU time increments ("ticks"), and is cumulative for all CPUs, so it may exceed the actual elapsed time. Multiply by @@TIMETICKS to convert to microseconds.

Note

If the time returned in @CPU_BUSY, or IO_BUSY exceeds approximately 49 days of cumulative CPU time, you receive an arithmetic overflow warning. In that case, the value of CPU_BUSY, IO_BUSY and @IDLE variables are not accurate.

Example:

SELECT @@IO_BUSY*@@TIMETICKS AS 'IO microseconds',
   GETDATE() AS 'as of';

__cursorRows :: SExp #

Origin documentation for __cursorRows

Syntax:

@@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.

Example:

USE AdventureWorks2012;
GO
SELECT @@CURSOR_ROWS;
DECLARE Name_Cursor CURSOR FOR
SELECT LastName ,@@CURSOR_ROWS FROM Person.Person;
OPEN Name_Cursor;
FETCH NEXT FROM Name_Cursor;
SELECT @@CURSOR_ROWS;
CLOSE Name_Cursor;
DEALLOCATE Name_Cursor;
GO

datediff #

Arguments

:: SExp 
-> SExp 
-> SExp

enddate

-> SExp 

Origin documentation for datediff

Syntax:

DATEDIFF ( datepart , startdate , enddate )

This function returns the count (as a signed integer value) of the specified datepart boundaries crossed between the specified startdate and enddate .

See DATEDIFF_BIG (Transact-SQL) for a function that handles larger differences between the startdate and enddate values. See Date and Time Data Types and Functions (Transact-SQL) for an overview of all Transact-SQL date and time data types and functions.

Example:

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(microsecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Example:

CREATE TABLE dbo.Duration
    (startDate datetime2, endDate datetime2);

INSERT INTO dbo.Duration(startDate, endDate)
    VALUES ('2007-05-06 12:10:09', '2007-05-07 12:10:09');

SELECT DATEDIFF(day, startDate, endDate) AS 'Duration'
    FROM dbo.Duration;
-- Returns: 1

Example:

DECLARE @startdate DATETIME2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate   DATETIME2 = '2007-05-04 12:10:09.3312722';
SELECT DATEDIFF(day, @startdate, @enddate);

Example:

SELECT DATEDIFF(millisecond, GETDATE(), SYSDATETIME());

Example:

USE AdventureWorks2012;
GO
SELECT DATEDIFF(day,
    (SELECT MIN(OrderDate) FROM Sales.SalesOrderHeader),
    (SELECT MAX(OrderDate) FROM Sales.SalesOrderHeader));

Example:

SELECT DATEDIFF(day,
   '2007-05-07 09:53:01.0376635',
   '2007-05-08 09:53:01.0376635');

Example:

USE AdventureWorks2012;
GO
SELECT DATEDIFF(day, '2007-05-07 09:53:01.0376635', GETDATE() + 1)
    AS NumberOfDays
    FROM Sales.SalesOrderHeader;
GO
USE AdventureWorks2012;
GO
SELECT
    DATEDIFF(
            day,
            '2007-05-07 09:53:01.0376635',
            DATEADD(day, 1, SYSDATETIME())
        ) AS NumberOfDays
    FROM Sales.SalesOrderHeader;
GO

Example:

USE AdventureWorks2012;
GO
SELECT p.FirstName, p.LastName
    ,DATEDIFF(day, ROW_NUMBER() OVER (ORDER BY
        a.PostalCode), SYSDATETIME()) AS 'Row Number'
FROM Sales.SalesPerson s
    INNER JOIN Person.Person p
        ON s.BusinessEntityID = p.BusinessEntityID
    INNER JOIN Person.Address a
        ON a.AddressID = p.BusinessEntityID
WHERE TerritoryID IS NOT NULL
    AND SalesYTD <> 0;

Example:

USE AdventureWorks2012;
GO
SELECT soh.SalesOrderID, sod.ProductID, sod.OrderQty, soh.OrderDate,
    DATEDIFF(day, MIN(soh.OrderDate)
        OVER(PARTITION BY soh.SalesOrderID), SYSDATETIME()) AS 'Total'
FROM Sales.SalesOrderDetail sod
    INNER JOIN Sales.SalesOrderHeader soh
        ON sod.SalesOrderID = soh.SalesOrderID
WHERE soh.SalesOrderID IN(43659, 58918);
GO

Example:

-- DOES NOT ACCOUNT FOR LEAP YEARS
DECLARE @date1 DATETIME, @date2 DATETIME, @result VARCHAR(100);
DECLARE @years INT, @months INT, @days INT,
    @hours INT, @minutes INT, @seconds INT, @milliseconds INT;

SET @date1 = '1900-01-01 00:00:00.000'
SET @date2 = '2018-12-12 07:08:01.123'

SELECT @years = DATEDIFF(yy, @date1, @date2)
IF DATEADD(yy, -@years, @date2) < @date1
SELECT @years = @years-1
SET @date2 = DATEADD(yy, -@years, @date2)

SELECT @months = DATEDIFF(mm, @date1, @date2)
IF DATEADD(mm, -@months, @date2) < @date1
SELECT @months=@months-1
SET @date2= DATEADD(mm, -@months, @date2)

SELECT @days=DATEDIFF(dd, @date1, @date2)
IF DATEADD(dd, -@days, @date2) < @date1
SELECT @days=@days-1
SET @date2= DATEADD(dd, -@days, @date2)

SELECT @hours=DATEDIFF(hh, @date1, @date2)
IF DATEADD(hh, -@hours, @date2) < @date1
SELECT @hours=@hours-1
SET @date2= DATEADD(hh, -@hours, @date2)

SELECT @minutes=DATEDIFF(mi, @date1, @date2)
IF DATEADD(mi, -@minutes, @date2) < @date1
SELECT @minutes=@minutes-1
SET @date2= DATEADD(mi, -@minutes, @date2)

SELECT @seconds=DATEDIFF(s, @date1, @date2)
IF DATEADD(s, -@seconds, @date2) < @date1
SELECT @seconds=@seconds-1
SET @date2= DATEADD(s, -@seconds, @date2)

SELECT @milliseconds=DATEDIFF(ms, @date1, @date2)

SELECT @result= ISNULL(CAST(NULLIF(@years,0) AS VARCHAR(10)) + ' years,','')
     + ISNULL(' ' + CAST(NULLIF(@months,0) AS VARCHAR(10)) + ' months,','')
     + ISNULL(' ' + CAST(NULLIF(@days,0) AS VARCHAR(10)) + ' days,','')
     + ISNULL(' ' + CAST(NULLIF(@hours,0) AS VARCHAR(10)) + ' hours,','')
     + ISNULL(' ' + CAST(@minutes AS VARCHAR(10)) + ' minutes and','')
     + ISNULL(' ' + CAST(@seconds AS VARCHAR(10))
     + CASE
            WHEN @milliseconds > 0
                THEN '.' + CAST(@milliseconds AS VARCHAR(10))
            ELSE ''
       END
     + ' seconds','')

SELECT @result

Example:

CREATE TABLE dbo.Duration
    (startDate datetime2, endDate datetime2);

INSERT INTO dbo.Duration (startDate, endDate)
    VALUES ('2007-05-06 12:10:09', '2007-05-07 12:10:09');

SELECT TOP(1) DATEDIFF(day, startDate, endDate) AS Duration
    FROM dbo.Duration;
-- Returns: 1

Example:

-- Uses AdventureWorks

SELECT TOP(1) DATEDIFF(day, (SELECT MIN(HireDate) FROM dbo.DimEmployee),
    (SELECT MAX(HireDate) FROM dbo.DimEmployee))
FROM dbo.DimEmployee;

Example:

-- Uses AdventureWorks

SELECT TOP(1) DATEDIFF(day,
    '2007-05-07 09:53:01.0376635',
    '2007-05-08 09:53:01.0376635') FROM DimCustomer;

Example:

-- Uses AdventureWorks

SELECT FirstName, LastName,
    DATEDIFF(day, ROW_NUMBER() OVER (ORDER BY
        DepartmentName), SYSDATETIME()) AS RowNumber
FROM dbo.DimEmployee;

Example:

-- Uses AdventureWorks

SELECT FirstName, LastName, DepartmentName,
    DATEDIFF(year, MAX(HireDate)
        OVER (PARTITION BY DepartmentName), SYSDATETIME()) AS SomeValue
FROM dbo.DimEmployee

lower #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for lower

Syntax:

LOWER ( character_expression )

Returns a character expression after converting uppercase character data to lowercase.

Example:

-- Uses AdventureWorks

SELECT LOWER(SUBSTRING(EnglishProductName, 1, 20)) AS Lower,
       UPPER(SUBSTRING(EnglishProductName, 1, 20)) AS Upper,
       LOWER(UPPER(SUBSTRING(EnglishProductName, 1, 20))) As LowerUpper
FROM dbo.DimProduct
WHERE ListPrice between 11.00 and 20.00;

loginProperty #

Arguments

:: SExp 
-> SExp

propertyName

-> SExp 

Origin documentation for loginProperty

Syntax:

LOGINPROPERTY ( 'login_name' , 'property_name' )

Returns information about login policy settings.

Example:

SELECT LOGINPROPERTY('John3', 'IsMustChange');
GO

Example:

SELECT LOGINPROPERTY('John3', 'IsLocked');
GO

stdevp #

Arguments

:: Maybe Distinctness 
-> SExp

expression

-> SExp 

Origin documentation for stdevp

Syntax:

-- Aggregate Function Syntax
STDEVP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEVP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation for the population for all values in the specified expression.

Example:

SELECT STDEVP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEVP(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEVP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;SELECT STDEVP(DISTINCT Quantity)AS Distinct_Values, STDEVP(Quantity) AS All_Values
FROM ProductInventory;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEVP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

iif #

Arguments

:: SExp 
-> SExp 
-> SExp

falseValue

-> SExp 

Origin documentation for iif

Syntax:

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.

Example:

DECLARE @a INT = 45, @b INT = 40;
SELECT [Result] = IIF( @a > @b, 'TRUE', 'FALSE' );

Example:

SELECT [Result] = IIF( 45 > 30, NULL, NULL );

Example:

DECLARE @P INT = NULL, @S INT = NULL;
SELECT [Result] = IIF( 45 > 30, @P, @S );

objectPropertyex #

Arguments

:: SExp 
-> SExp

property

-> SExp 

Origin documentation for objectPropertyex

Syntax:

OBJECTPROPERTYEX ( id , property )

Returns information about schema-scoped objects in the current database. For a list of these objects, see sys.objects (Transact-SQL) . OBJECTPROPERTYEX cannot be used for objects that are not schema-scoped, such as data definition language (DDL) triggers and event notifications.

Example:

USE master;
GO
SELECT OBJECTPROPERTYEX(OBJECT_ID(N'AdventureWorks2012.HumanResources.vEmployee'), 'IsView');
GO

Example:

USE AdventureWorks2012;
GO
CREATE SYNONYM MyEmployeeTable FOR HumanResources.Employee;
GO
SELECT OBJECTPROPERTYEX ( object_id(N'MyEmployeeTable'), N'BaseType')AS [Base Type];
GO

Example:

USE AdventureWorks2012;
GO
SELECT OBJECTPROPERTYEX(OBJECT_ID(N'HumanResources.Employee'), N'TABLEUPDATETRIGGERCOUNT');
GO

Example:

USE AdventureWorks2012;
GO
SELECT name, object_id, schema_id, type_desc
FROM sys.objects
WHERE OBJECTPROPERTYEX(object_id, N'TableHasForeignKey') = 1
ORDER BY name;
GO

Example:

-- Uses AdventureWorks

SELECT OBJECTPROPERTYEX ( object_id(N'dbo.DimReseller'), N'BaseType')AS BaseType;

translate #

Arguments

:: SExp 
-> SExp 
-> SExp

translations

-> SExp 

Origin documentation for translate

Syntax:

TRANSLATE ( inputString, characters, translations )

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.

Example:

SELECT TRANSLATE('2*[3+4]/{7-2}', '[]{}', '()()');

Example:

SELECT
REPLACE
(
      REPLACE
      (
            REPLACE
            (
                  REPLACE
                  (
                        '2*[3+4]/{7-2}',
                        '[',
                        '('
                  ),
                  ']',
                  ')'
            ),
            '{',
            '('
      ),
      '}',
      ')'
);

Example:

SELECT TRANSLATE('[137.4,72.3]' , '[,]', '( )') AS Point,
    TRANSLATE('(137.4 72.3)' , '( )', '[,]') AS Coordinates;

Example:

SELECT TRANSLATE('abcdef','abc','bcd') AS Translated,
       REPLACE(REPLACE(REPLACE('abcdef','a','b'),'b','c'),'c','d') AS Replaced;

sysDateTime :: SExp #

Origin documentation for sysDateTime

Syntax:

SYSDATETIME ( )

Returns a datetime2(7) value that contains the date and time of the computer on which the instance of SQL Server is running.

Note

SYSDATETIME and SYSUTCDATETIME have more fractional seconds precision than GETDATE and GETUTCDATE. SYSDATETIMEOFFSET includes the system time zone offset. SYSDATETIME, SYSUTCDATETIME, and SYSDATETIMEOFFSET can be assigned to a variable of any of the date and time types.

Azure SQL Database (with the exception of Azure SQL Managed Instance) and Azure Synapse Analytics follow UTC. Use AT TIME ZONE in Azure SQL Database or Azure Synapse Analytics if you need to interpret date and time information in a non-UTC time zone.

For an overview of all Transact-SQL date and time data types and functions, see Date and Time Data Types and Functions (Transact-SQL) .

Example:

SELECT SYSDATETIME()
    ,SYSDATETIMEOFFSET()
    ,SYSUTCDATETIME()
    ,CURRENT_TIMESTAMP
    ,GETDATE()
    ,GETUTCDATE();
/* Returned:
SYSDATETIME()      2007-04-30 13:10:02.0474381
SYSDATETIMEOFFSET()2007-04-30 13:10:02.0474381 -07:00
SYSUTCDATETIME()   2007-04-30 20:10:02.0474381
CURRENT_TIMESTAMP  2007-04-30 13:10:02.047
GETDATE()          2007-04-30 13:10:02.047
GETUTCDATE()       2007-04-30 20:10:02.047
*/

Example:

SELECT CONVERT (date, SYSDATETIME())
    ,CONVERT (date, SYSDATETIMEOFFSET())
    ,CONVERT (date, SYSUTCDATETIME())
    ,CONVERT (date, CURRENT_TIMESTAMP)
    ,CONVERT (date, GETDATE())
    ,CONVERT (date, GETUTCDATE());

/* All returned 2007-04-30 */

Example:

SELECT CONVERT (time, SYSDATETIME())
    ,CONVERT (time, SYSDATETIMEOFFSET())
    ,CONVERT (time, SYSUTCDATETIME())
    ,CONVERT (time, CURRENT_TIMESTAMP)
    ,CONVERT (time, GETDATE())
    ,CONVERT (time, GETUTCDATE());

/* Returned
SYSDATETIME()      13:18:45.3490361
SYSDATETIMEOFFSET()13:18:45.3490361
SYSUTCDATETIME()   20:18:45.3490361
CURRENT_TIMESTAMP  13:18:45.3470000
GETDATE()          13:18:45.3470000
GETUTCDATE()       20:18:45.3470000
*/

Example:

SELECT SYSDATETIME();

upper #

Arguments

:: SExp

characterExpression

-> SExp 

Origin documentation for upper

Syntax:

UPPER ( character_expression )

Returns a character expression with lowercase character data converted to uppercase.

Example:

-- Uses AdventureWorks

SELECT UPPER(RTRIM(LastName)) + ', ' + FirstName AS Name
FROM dbo.DimEmployee
ORDER BY LastName;

char #

Arguments

:: SExp

integerExpression

-> SExp 

Origin documentation for char

Syntax:

CHAR ( integer_expression )

Returns the single-byte character with the specified integer code, as defined by the character set and encoding of the default collation of the current database.

Example:

SET TEXTSIZE 0;
-- Create variables for the character string and for the current
-- position in the string.
DECLARE @position INT, @string CHAR(8);
-- Initialize the current position and the string variables.
SET @position = 1;
SET @string = 'New Moon';
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)),
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
   SET @position = @position + 1
   END;
GO

Example:

SELECT p.FirstName + ' ' + p.LastName, + CHAR(13)  + pe.EmailAddress
FROM Person.Person p
INNER JOIN Person.EmailAddress pe ON p.BusinessEntityID = pe.BusinessEntityID
  AND p.BusinessEntityID = 1;
GO

Example:

SELECT CHAR(65) AS [65], CHAR(66) AS [66],
CHAR(97) AS [97], CHAR(98) AS [98],
CHAR(49) AS [49], CHAR(50) AS [50];

Example:

SELECT name, 'was created on ', create_date, CHAR(13), name, 'is currently ', state_desc
FROM sys.databases;
GO

Example:

SELECT CHAR(188) AS single_byte_representing_complete_character,
  CHAR(0xBC) AS single_byte_representing_complete_character;
GO

Example:

SELECT CHAR(129) AS first_byte_of_double_byte_character,
  CHAR(0x81) AS first_byte_of_double_byte_character;
GO

Example:

CREATE DATABASE [multibyte-char-context]
  COLLATE Japanese_CI_AI
GO
USE [multibyte-char-context]
GO
SELECT NCHAR(0x266A) AS [eighth-note]
  , CONVERT(CHAR(2), 0x81F4) AS [context-dependent-convert]
  , CAST(0x81F4 AS CHAR(2)) AS [context-dependent-cast]

Example:

; WITH uni(c) AS (
    -- BMP character
    SELECT NCHAR(9835)
    UNION ALL
    -- non-BMP supplementary character or, under downlevel collation, NULL
    SELECT NCHAR(127925)
  ),
  enc(u16c, u8c) AS (
    SELECT c, CONVERT(VARCHAR(4), c COLLATE Latin1_General_100_CI_AI_SC_UTF8)
    FROM uni
  )
  SELECT u16c AS [Music note]
    , u8c AS [Music note (UTF-8)]
    , UNICODE(u16c) AS [Code Point]
    , CONVERT(VARBINARY(4), u16c) AS [UTF-16LE bytes]
    , CONVERT(VARBINARY(4), u8c)  AS [UTF-8 bytes]
  FROM enc

dateTrunc #

Arguments

:: SExp 
-> SExp

date

-> SExp 

Origin documentation for dateTrunc

Syntax:

DATETRUNC ( datepart, date )

Starting with SQL Server 2022 (16.x), this function returns an input date truncated to a specified datepart .

Example:

DECLARE @d datetime2 = '2021-12-08 11:30:15.1234567';
SELECT 'Year', DATETRUNC(year, @d);
SELECT 'Quarter', DATETRUNC(quarter, @d);
SELECT 'Month', DATETRUNC(month, @d);
SELECT 'Week', DATETRUNC(week, @d); -- Using the default DATEFIRST setting value of 7 (U.S. English)
SELECT 'Iso_week', DATETRUNC(iso_week, @d);
SELECT 'DayOfYear', DATETRUNC(dayofyear, @d);
SELECT 'Day', DATETRUNC(day, @d);
SELECT 'Hour', DATETRUNC(hour, @d);
SELECT 'Minute', DATETRUNC(minute, @d);
SELECT 'Second', DATETRUNC(second, @d);
SELECT 'Millisecond', DATETRUNC(millisecond, @d);
SELECT 'Microsecond', DATETRUNC(microsecond, @d);

Example:

DECLARE @d datetime2 = '2021-11-11 11:11:11.1234567';

SELECT 'Week-7', DATETRUNC(week, @d); -- Uses the default DATEFIRST setting value of 7 (U.S. English)

SET DATEFIRST 6;
SELECT 'Week-6', DATETRUNC(week, @d);

SET DATEFIRST 3;
SELECT 'Week-3', DATETRUNC(week, @d);

Example:

SELECT DATETRUNC(month, '1998-03-04');

SELECT DATETRUNC(millisecond, '1998-03-04 10:10:05.1234567');

DECLARE @d1 char(200) = '1998-03-04';
SELECT DATETRUNC(millisecond, @d1);

DECLARE @d2 nvarchar(max) = '1998-03-04 10:10:05';
SELECT DATETRUNC(minute, @d2);

Example:

DECLARE @d datetime2 = '1998-12-11 02:03:04.1234567';
SELECT DATETRUNC(day, @d);

Example:

USE WideWorldImporters;

SELECT CustomerTransactionID,
    DATETRUNC(month, TransactionDate) AS MonthTransactionOccurred,
    InvoiceID,
    CustomerID,
    TransactionAmount,
    SUM(TransactionAmount) OVER (
        PARTITION BY CustomerID ORDER BY TransactionDate,
            CustomerTransactionID ROWS UNBOUNDED PRECEDING
        ) AS RunningTotal,
    TransactionDate AS ActualTransactionDate
FROM [WideWorldImporters].[Sales].[CustomerTransactions]
WHERE InvoiceID IS NOT NULL
    AND DATETRUNC(month, TransactionDate) >= '2015-12-01';

Example:

SELECT DATETRUNC(m, SYSDATETIME());

SELECT DATETRUNC(yyyy, CONVERT(date, '2021-12-1'));

USE WideWorldImporters;
GO
SELECT DATETRUNC(month, DATEADD(month, 4, TransactionDate))
FROM Sales.CustomerTransactions;
GO

Example:

DECLARE @d datetime = '2015-04-29 05:06:07.123';
SELECT 'Input', @d;
SELECT 'Truncated', DATETRUNC(millisecond, @d);

Example:

DECLARE @d date = '2050-04-04';
SELECT 'Input', @d;
SELECT 'Truncated', DATETRUNC(day, @d);

Example:

DECLARE @d smalldatetime = '2009-09-11 12:42:12'
SELECT 'Input', @d;
SELECT 'Truncated to minute', DATETRUNC(minute, @d)
SELECT 'Truncated to second', DATETRUNC(second, @d);

Example:

DECLARE @d datetime = '2020-02-02 02:02:02.002';
SELECT 'Input', @d;
SELECT 'Truncated', DATETRUNC(millisecond, @d);

Example:

DECLARE @d date= '0001-01-01 00:00:00';
SELECT DATETRUNC(week, @d);

Example:

DECLARE @d time = '12:12:12.1234567';
SELECT DATETRUNC(year, @d);

Example:

DECLARE @d datetime2(3) = '2021-12-12 12:12:12.12345';
SELECT DATETRUNC(microsecond, @d);

errorMessage :: SExp #

Origin documentation for errorMessage

Syntax:

ERROR_MESSAGE ( )

This function returns the message text of the error that caused the CATCH block of a TRY...CATCH construct to execute.

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

Example:

BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
END TRY
BEGIN CATCH
    SELECT
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

msaVarp_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaVarp_ALL

Syntax:

-- Aggregate Function Syntax
VARP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VARP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance for the population for all values in the specified expression.

Example:

SELECT VARP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VARP(DISTINCT SalesAmountQuota)AS Distinct_Values, VARP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VARP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaVarp #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaVarp

Syntax:

-- Aggregate Function Syntax
VARP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VARP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance for the population for all values in the specified expression.

Example:

SELECT VARP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VARP(DISTINCT SalesAmountQuota)AS Distinct_Values, VARP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VARP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaSum_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaSum_ALL

Syntax:

-- Aggregate Function Syntax
SUM ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
SUM ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

Example:

SELECT Color, SUM(ListPrice), SUM(StandardCost)
FROM Production.Product
WHERE Color IS NOT NULL
    AND ListPrice != 0.00
    AND Name LIKE 'Mountain%'
GROUP BY Color
ORDER BY Color;
GO

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                           ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY TerritoryID,SalesYear;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY SalesYear;

Example:

-- Uses AdventureWorks

SELECT ProductKey, SUM(SalesAmount) AS TotalPerProduct
FROM dbo.FactInternetSales
WHERE OrderDateKey >= '20030101'
      AND OrderDateKey < '20040101'
GROUP BY ProductKey
ORDER BY ProductKey;

Example:

-- Uses AdventureWorks

SELECT Color, SUM(ListPrice)AS TotalList,
       SUM(StandardCost) AS TotalCost
FROM dbo.DimProduct
GROUP BY Color
ORDER BY Color;

msaSum #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaSum

Syntax:

-- Aggregate Function Syntax
SUM ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
SUM ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

Example:

SELECT Color, SUM(ListPrice), SUM(StandardCost)
FROM Production.Product
WHERE Color IS NOT NULL
    AND ListPrice != 0.00
    AND Name LIKE 'Mountain%'
GROUP BY Color
ORDER BY Color;
GO

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                           ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (PARTITION BY TerritoryID
                                            ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY TerritoryID,SalesYear;

Example:

SELECT BusinessEntityID, TerritoryID
   ,DATEPART(yy,ModifiedDate) AS SalesYear
   ,CONVERT(VARCHAR(20),SalesYTD,1) AS  SalesYTD
   ,CONVERT(VARCHAR(20),AVG(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS MovingAvg
   ,CONVERT(VARCHAR(20),SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)
                                            ),1) AS CumulativeTotal
FROM Sales.SalesPerson
WHERE TerritoryID IS NULL OR TerritoryID < 5
ORDER BY SalesYear;

Example:

-- Uses AdventureWorks

SELECT ProductKey, SUM(SalesAmount) AS TotalPerProduct
FROM dbo.FactInternetSales
WHERE OrderDateKey >= '20030101'
      AND OrderDateKey < '20040101'
GROUP BY ProductKey
ORDER BY ProductKey;

Example:

-- Uses AdventureWorks

SELECT Color, SUM(ListPrice)AS TotalList,
       SUM(StandardCost) AS TotalCost
FROM dbo.DimProduct
GROUP BY Color
ORDER BY Color;

msaCountBig_ALL_STAR #

Arguments

:: Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCountBig_ALL_STAR

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

msaCountBig_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCountBig_ALL

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

msaCountBig_STAR #

Arguments

:: Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCountBig_STAR

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

msaCountBig #

Arguments

:: SExp 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCountBig

Syntax:

-- Aggregation Function Syntax
COUNT_BIG ( { [ [ ALL | DISTINCT ] expression ] | * } )

-- Analytic Function Syntax
COUNT_BIG ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT_BIG operates like the COUNT function. These functions differ only in the data types of their return values. COUNT_BIG always returns a bigint data type value. COUNT always returns an int data type value.

msaStdev_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaStdev_ALL

Syntax:

-- Aggregate Function Syntax
STDEV ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEV ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation of all values in the specified expression.

Example:

SELECT STDEV(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEV(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEV(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEV(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaStdev #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaStdev

Syntax:

-- Aggregate Function Syntax
STDEV ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEV ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation of all values in the specified expression.

Example:

SELECT STDEV(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEV(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEV(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEV(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaVar_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaVar_ALL

Syntax:

-- Aggregate Function Syntax
VAR ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VAR ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance of all values in the specified expression. May be followed by the OVER clause .

Example:

SELECT VAR(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VAR(DISTINCT SalesAmountQuota)AS Distinct_Values, VAR(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VAR(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaVar #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaVar

Syntax:

-- Aggregate Function Syntax
VAR ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
VAR ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical variance of all values in the specified expression. May be followed by the OVER clause .

Example:

SELECT VAR(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT VAR(DISTINCT SalesAmountQuota)AS Distinct_Values, VAR(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       VAR(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS Variance
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaMax_ALL #

Arguments

:: SExp 
-> PartitionBy 
-> Maybe OverOrderBy

maybeOverorderby

-> SExp 

Origin documentation for msaMax_ALL

Syntax:

-- Aggregation Function Syntax
MAX( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MAX ([ ALL ] expression) OVER ( <partition_by_clause> [ <order_by_clause> ] )

Returns the maximum value in the expression.

Example:

SELECT MAX(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

SELECT MAX(name) FROM sys.databases WHERE database_id < 5;

msaMax #

Arguments

:: SExp 
-> PartitionBy 
-> Maybe OverOrderBy

maybeOverorderby

-> SExp 

Origin documentation for msaMax

Syntax:

-- Aggregation Function Syntax
MAX( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MAX ([ ALL ] expression) OVER ( <partition_by_clause> [ <order_by_clause> ] )

Returns the maximum value in the expression.

Example:

SELECT MAX(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

SELECT MAX(name) FROM sys.databases WHERE database_id < 5;

msaMin_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> Maybe OverOrderBy

maybeOverorderby

-> SExp 

Origin documentation for msaMin_ALL

Syntax:

-- Aggregation Function Syntax
MIN ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MIN ( [ ALL ] expression ) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] )

Returns the minimum value in the expression. May be followed by the OVER clause .

Example:

SELECT MIN(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice)
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664');

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice) OVER(PARTITION BY SalesOrderNumber) AS LeastExpensiveProduct,
       SalesOrderNumber
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664')
ORDER BY SalesOrderNumber;

msaMin #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> Maybe OverOrderBy

maybeOverorderby

-> SExp 

Origin documentation for msaMin

Syntax:

-- Aggregation Function Syntax
MIN ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
MIN ( [ ALL ] expression ) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] )

Returns the minimum value in the expression. May be followed by the OVER clause .

Example:

SELECT MIN(TaxRate)
FROM Sales.SalesTaxRate;
GO

Example:

SELECT DISTINCT Name
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
     ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
 ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice)
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664');

Example:

-- Uses AdventureWorks

SELECT DISTINCT MIN(UnitPrice) OVER(PARTITION BY SalesOrderNumber) AS LeastExpensiveProduct,
       SalesOrderNumber
FROM dbo.FactResellerSales
WHERE SalesOrderNumber IN (N'SO43659', N'SO43660', N'SO43664')
ORDER BY SalesOrderNumber;

msaStdevp_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaStdevp_ALL

Syntax:

-- Aggregate Function Syntax
STDEVP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEVP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation for the population for all values in the specified expression.

Example:

SELECT STDEVP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEVP(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEVP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;SELECT STDEVP(DISTINCT Quantity)AS Distinct_Values, STDEVP(Quantity) AS All_Values
FROM ProductInventory;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEVP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaStdevp #

Arguments

:: SExp 
-> Maybe PartitionBy 
-> OverOrderBy

overorderby

-> SExp 

Origin documentation for msaStdevp

Syntax:

-- Aggregate Function Syntax
STDEVP ( [ ALL | DISTINCT ] expression )

-- Analytic Function Syntax
STDEVP ([ ALL ] expression) OVER ( [ partition_by_clause ] order_by_clause)

Returns the statistical standard deviation for the population for all values in the specified expression.

Example:

SELECT STDEVP(Bonus)
FROM Sales.SalesPerson;
GO

Example:

-- Uses AdventureWorks

SELECT STDEVP(DISTINCT SalesAmountQuota)AS Distinct_Values, STDEVP(SalesAmountQuota) AS All_Values
FROM dbo.FactSalesQuota;SELECT STDEVP(DISTINCT Quantity)AS Distinct_Values, STDEVP(Quantity) AS All_Values
FROM ProductInventory;

Example:

-- Uses AdventureWorks

SELECT CalendarYear AS Year, CalendarQuarter AS Quarter, SalesAmountQuota AS SalesQuota,
       STDEVP(SalesAmountQuota) OVER (ORDER BY CalendarYear, CalendarQuarter) AS StdDeviation
FROM dbo.FactSalesQuota
WHERE EmployeeKey = 272 AND CalendarYear = 2002
ORDER BY CalendarQuarter;

msaCount_ALL_STAR #

Arguments

:: Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCount_ALL_STAR

Syntax:

COUNT ( [ ALL ]  { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msaCount_ALL #

Arguments

:: SExp 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCount_ALL

Syntax:

COUNT ( [ ALL ]  { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msaCount_STAR #

Arguments

:: Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCount_STAR

Syntax:

COUNT ( [ ALL ]  { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');

msaCount #

Arguments

:: SExp 
-> Maybe PartitionBy

maybePartitionby

-> SExp 

Origin documentation for msaCount

Syntax:

COUNT ( [ ALL ]  { expression | * } ) OVER ( [ <partition_by_clause> ] )

This function returns the number of items found in a group. COUNT operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT always returns an int data type value. COUNT_BIG always returns a bigint data type value.

Example:

SELECT COUNT(DISTINCT Title)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*)
FROM HumanResources.Employee;
GO

Example:

SELECT COUNT(*), AVG(Bonus)
FROM Sales.SalesPerson
WHERE SalesQuota > 25000;
GO

Example:

SELECT DISTINCT Name
    , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary
    , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary
    , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary
    , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept
FROM HumanResources.EmployeePayHistory AS eph
JOIN HumanResources.EmployeeDepartmentHistory AS edh
    ON eph.BusinessEntityID = edh.BusinessEntityID
JOIN HumanResources.Department AS d
ON d.DepartmentID = edh.DepartmentID
WHERE edh.EndDate IS NULL
ORDER BY Name;

Example:

USE ssawPDW;

SELECT COUNT(DISTINCT Title)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(*)
FROM dbo.DimEmployee;

Example:

USE ssawPDW;

SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota]
FROM dbo.FactSalesQuota
WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;

Example:

USE ssawPDW;

SELECT DepartmentName,
    COUNT(EmployeeKey)AS EmployeesInDept
FROM dbo.DimEmployee
GROUP BY DepartmentName
HAVING COUNT(EmployeeKey) > 15;

Example:

USE ssawPDW;

SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount
    , SalesOrderNumber
FROM dbo.FactInternetSales
WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');