Safe Haskell | None |
---|---|
Language | GHC2024 |
Module exposes Sql Server API
as Haskell functions for SExp
generated out of MSDN specs.
Synopsis
- msCount :: SExp
- msCount_Distinctness :: Maybe Distinctness -> SExp -> SExp
- msCount_STAR :: SExp
- msCast :: SExp -> SExp -> SExp
- msCast_Length :: SExp -> SExp -> SExp -> SExp
- msConvert :: SExp -> SExp -> SExp
- msConvert_Style :: SExp -> SExp -> SExp -> SExp
- msConvert_Length :: SExp -> SExp -> SExp -> SExp
- msConvert_Length_Style :: SExp -> SExp -> SExp -> SExp -> SExp
- msSign :: SExp -> SExp
- msAvg :: Maybe Distinctness -> SExp -> SExp
- msAvg_OVER :: Maybe Distinctness -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msIsNull :: SExp -> SExp -> SExp
- msConcat :: SExp -> NonEmpty SExp -> SExp
- msVar :: Maybe Distinctness -> SExp -> SExp
- msMax :: Maybe Distinctness -> SExp -> SExp
- msAbs :: SExp -> SExp
- msMin :: Maybe Distinctness -> SExp -> SExp
- msSum :: Maybe Distinctness -> SExp -> SExp
- formatMessage :: SExp -> SExp
- formatMessage_ParamValue :: SExp -> NonEmpty SExp -> SExp
- decryptByPassPhrase :: SExp -> SExp -> SExp
- decryptByPassPhrase_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp -> SExp
- cryptGenRandom :: SExp -> SExp
- cryptGenRandom_Seed :: SExp -> SExp -> SExp
- lead :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- lead_Default :: SExp -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- lead_Offset :: SExp -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- lead_Offset_Default :: SExp -> SExp -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- objectName :: SExp -> SExp
- objectName_DatabaseId :: SExp -> SExp -> SExp
- round :: SExp -> SExp -> SExp
- round_Function :: SExp -> SExp -> SExp -> SExp
- getAnsiNull :: SExp
- getAnsiNull_Database :: SExp -> SExp
- ntile :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- decryptByKeyAutoAsymKey :: SExp -> SExp -> SExp -> SExp
- decryptByKeyAutoAsymKey_AddAuthenticator :: SExp -> SExp -> SExp -> SExp -> SExp
- decryptByKeyAutoAsymKey_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- asymKeyProperty_KeyId_AlgorithmDesc :: SExp -> SExp -> SExp
- asymKeyProperty_StringSid :: SExp -> SExp
- asymKeyProperty_Sid :: SExp -> SExp
- encryptByPassPhrase :: SExp -> SExp -> SExp
- encryptByPassPhrase_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp -> SExp
- decryptByKeyAutoCert :: SExp -> SExp -> SExp -> SExp
- decryptByKeyAutoCert_AddAuthenticator :: SExp -> SExp -> SExp -> SExp -> SExp
- decryptByKeyAutoCert_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- triggerNestLevel :: SExp
- triggerNestLevel_TriggerType :: SExp -> SExp
- triggerNestLevel_TriggerType_TriggerEventCategory :: SExp -> SExp -> SExp
- triggerNestLevel_ObjectId :: SExp -> SExp
- triggerNestLevel_ObjectId_TriggerType :: SExp -> SExp -> SExp
- triggerNestLevel_ObjectId_TriggerType_TriggerEventCategory :: SExp -> SExp -> SExp -> SExp
- dateBucket :: SExp -> SExp -> SExp -> SExp
- dateBucket_Origin :: SExp -> SExp -> SExp -> SExp -> SExp
- dbName :: SExp
- dbName_DatabaseId :: SExp -> SExp
- decryptByAsymKey :: SExp -> SExp -> SExp
- decryptByAsymKey_AsymKeyPassword :: SExp -> SExp -> SExp -> SExp
- signByAsymKey :: SExp -> SExp -> SExp
- signByAsymKey_Password :: SExp -> SExp -> SExp -> SExp
- signByCert :: SExp -> SExp -> SExp
- signByCert_Password :: SExp -> SExp -> SExp -> SExp
- percentRank :: Maybe PartitionBy -> OverOrderBy -> SExp
- objectSchemaName :: SExp -> SExp
- objectSchemaName_DatabaseId :: SExp -> SExp -> SExp
- suserSid :: SExp
- suserSid_Param2 :: SExp -> SExp
- suserSid_Login :: SExp -> SExp
- suserSid_Login_Param2 :: SExp -> SExp -> SExp
- decryptByKey :: SExp -> SExp
- decryptByKey_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp
- charIndex :: SExp -> SExp -> SExp
- charIndex_StartLocation :: SExp -> SExp -> SExp -> SExp
- lag :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- lag_Offset :: SExp -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- lag_Offset_Default :: SExp -> SExp -> SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- certprivateKey :: SExp -> SExp -> SExp
- certprivateKey_DecryptionPassword :: SExp -> SExp -> SExp -> SExp
- cumeDist :: Maybe PartitionBy -> OverOrderBy -> SExp
- dbId :: SExp
- dbId_DatabaseName :: SExp -> SExp
- isMember_Group :: SExp -> SExp
- isMember_Role :: SExp -> SExp
- hasPermsByName :: SExp -> SExp -> SExp -> SExp
- hasPermsByName_SubSecurable :: SExp -> SExp -> SExp -> SExp -> SExp
- hasPermsByName_SubSecurable_SubSecurableClass :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- typeId :: SExp -> SExp
- typeId_SchemaName :: SExp -> SExp -> SExp
- jsonArray :: [SExp] -> Maybe JsonNullStrategy -> SExp
- symKeyProperty_KeyId_AlgorithmDesc :: SExp -> SExp -> SExp
- symKeyProperty_StringSid :: SExp -> SExp
- symKeyProperty_Sid :: SExp -> SExp
- permissions :: SExp
- permissions_Objectid :: SExp -> SExp
- permissions_Objectid_Column :: SExp -> SExp -> SExp
- isJson :: SExp -> SExp
- isJson_JsonTypeConstraint :: SExp -> SExp -> SExp
- userName :: SExp
- userName_Id :: SExp -> SExp
- countBig :: SExp
- countBig_Distinctness :: Maybe Distinctness -> SExp -> SExp
- countBig_STAR :: SExp
- userId :: SExp
- userId_User :: SExp -> SExp
- isSrvroleMember :: SExp -> SExp
- isSrvroleMember_Login :: SExp -> SExp -> SExp
- keyName_Ciphertext :: SExp -> SExp
- keyName_KeyGuid :: SExp -> SExp
- jsonObject :: [(SExp, SExp)] -> Maybe JsonNullStrategy -> SExp
- objectId :: SExp -> SExp
- objectId_ObjectType :: SExp -> SExp -> SExp
- objectId_DatabaseName :: SExp -> SExp -> SExp
- objectId_DatabaseName_ObjectType :: SExp -> SExp -> SExp -> SExp
- objectId_DatabaseName_SchemaName :: SExp -> SExp -> SExp -> SExp
- objectId_DatabaseName_SchemaName_ObjectType :: SExp -> SExp -> SExp -> SExp -> SExp
- objectId_SchemaName :: SExp -> SExp -> SExp
- objectId_SchemaName_ObjectType :: SExp -> SExp -> SExp -> SExp
- suserSName :: SExp
- suserSName_ServerUserSid :: SExp -> SExp
- format :: SExp -> SExp -> SExp
- format_Culture :: SExp -> SExp -> SExp -> SExp
- percentileDisc :: SExp -> SExp -> Maybe OrderDir -> Maybe PartitionBy -> SExp
- jsonQuery :: SExp -> SExp
- jsonQuery_Path :: SExp -> SExp -> SExp
- rand :: SExp
- rand_Seed :: SExp -> SExp
- tryCast :: SExp -> SExp -> SExp
- tryCast_Length :: SExp -> SExp -> SExp -> SExp
- log :: SExp -> SExp
- log_Base :: SExp -> SExp -> SExp
- eomonth :: SExp -> SExp
- eomonth_MonthToAdd :: SExp -> SExp -> SExp
- decryptByCert :: SExp -> SExp -> SExp
- decryptByCert_CertPassword :: SExp -> SExp -> SExp -> SExp
- str :: SExp -> SExp
- str_Length :: SExp -> SExp -> SExp
- str_Length_Decimal :: SExp -> SExp -> SExp -> SExp
- suserId :: SExp
- suserId_Login :: SExp -> SExp
- suserName :: SExp
- suserName_ServerUserId :: SExp -> SExp
- encryptByKey :: SExp -> SExp -> SExp
- encryptByKey_AddAuthenticator_Authenticator :: SExp -> SExp -> SExp -> SExp -> SExp
- indexCol :: SExp -> SExp -> SExp -> SExp
- indexCol_DatabaseName :: SExp -> SExp -> SExp -> SExp -> SExp
- indexCol_DatabaseName_SchemaName :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- indexCol_SchemaName :: SExp -> SExp -> SExp -> SExp -> SExp
- schemaId :: SExp
- schemaId_SchemaName :: SExp -> SExp
- denseRank :: Maybe PartitionBy -> OverOrderBy -> SExp
- tryConvert :: SExp -> SExp -> SExp
- tryConvert_Style :: SExp -> SExp -> SExp -> SExp
- tryConvert_Length :: SExp -> SExp -> SExp -> SExp
- tryConvert_Length_Style :: SExp -> SExp -> SExp -> SExp -> SExp
- quoteName :: SExp -> SExp
- quoteName_QuoteCharacter :: SExp -> SExp -> SExp
- schemaName :: SExp
- schemaName_SchemaId :: SExp -> SExp
- percentileCont :: SExp -> SExp -> Maybe OrderDir -> Maybe PartitionBy -> SExp
- isRoleMember :: SExp -> SExp
- isRoleMember_DatabasePrincipal :: SExp -> SExp -> SExp
- pwdCompare :: SExp -> SExp -> SExp
- pwdCompare_Version :: SExp -> SExp -> SExp -> SExp
- trim :: SExp -> SExp
- trim_FROM :: SExp -> SExp -> SExp
- trim_LEADING :: SExp -> SExp
- trim_LEADING_FROM :: SExp -> SExp -> SExp
- trim_TRAILING :: SExp -> SExp
- trim_TRAILING_FROM :: SExp -> SExp -> SExp
- trim_BOTH :: SExp -> SExp
- trim_BOTH_FROM :: SExp -> SExp -> SExp
- setBit :: SExp -> SExp -> SExp -> SExp
- originalLogin :: SExp
- identIncr :: SExp -> SExp
- identSeed :: SExp -> SExp
- timeFromParts :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- rightShift :: SExp -> SExp -> SExp
- iif :: SExp -> SExp -> SExp -> SExp
- replicate :: SExp -> SExp -> SExp
- concatWs :: SExp -> SExp -> NonEmpty SExp -> SExp
- jsonModify :: SExp -> SExp -> SExp -> SExp
- loginProperty :: SExp -> SExp -> SExp
- filePropertyex :: SExp -> SExp -> SExp
- sqrt :: SExp -> SExp
- getBit :: SExp -> SExp -> SExp
- fileProperty :: SExp -> SExp -> SExp
- __procid :: SExp
- typeName :: SExp -> SExp
- currentTransactionId :: SExp
- __maxConnections :: SExp
- __language :: SExp
- day :: SExp -> SExp
- edgeIdFromParts :: SExp -> SExp -> SExp
- __packReceived :: SExp
- compress :: SExp -> SExp
- __lockTimeout :: SExp
- atan :: SExp -> SExp
- __cpuBusy :: SExp
- dateTimeFromParts :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- checksum_STAR :: SExp
- checksum :: NonEmpty SExp -> SExp
- fileId :: SExp -> SExp
- cot :: SExp -> SExp
- sessionUser :: SExp
- pwdEncrypt :: SExp -> SExp
- sin :: SExp -> SExp
- columnProperty :: SExp -> SExp -> SExp -> SExp
- replace :: SExp -> SExp -> SExp -> SExp
- acos :: SExp -> SExp
- tan :: SExp -> SExp
- __connections :: SExp
- __serverName :: SExp
- errorState :: SExp
- char :: SExp -> SExp
- fileGroupId :: SExp -> SExp
- ascii :: SExp -> SExp
- __dbts :: SExp
- datediff :: SExp -> SExp -> SExp -> SExp
- __totalRead :: SExp
- square :: SExp -> SExp
- stuff :: SExp -> SExp -> SExp -> SExp -> SExp
- currentRequestId :: SExp
- rowNumber :: OverOrderBy -> SExp
- rowNumber_PARTITION_BY :: NonEmpty SExp -> OverOrderBy -> SExp
- __textsize :: SExp
- __serviceName :: SExp
- groupingId :: NonEmpty SExp -> SExp
- certId :: SExp -> SExp
- pi :: SExp
- difference :: SExp -> SExp -> SExp
- graphIdFromEdgeId :: SExp -> SExp
- identCurrent :: SExp -> SExp
- smallDateTimeFromParts :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- reverse :: SExp -> SExp
- errorProcedure :: SExp
- substring :: SExp -> SExp -> SExp -> SExp
- contextInfo :: SExp
- currentTimeZone :: SExp
- errorSeverity :: SExp
- certencoded :: SExp -> SExp
- dateTime2FromParts :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- __packSent :: SExp
- assemblyProperty :: SExp -> SExp -> SExp
- currentUser :: SExp
- __identity :: SExp
- textptr :: SExp -> SExp
- objectPropertyex :: SExp -> SExp -> SExp
- lower :: SExp -> SExp
- errorNumber :: SExp
- __rowCount :: SExp
- dataLength :: SExp -> SExp
- __options :: SExp
- __Version :: SExp
- cursorStatus_LOCAL :: SExp -> SExp
- cursorStatus_GLOBAL :: SExp -> SExp
- cursorStatus_VARIABLE :: SExp -> SExp
- exp :: SExp -> SExp
- jsonPathExists :: SExp -> SExp -> SExp
- getDate :: SExp
- verifySignedByCert :: SExp -> SExp -> SExp -> SExp
- fileIdex :: SExp -> SExp
- newid :: SExp
- varp :: Maybe Distinctness -> SExp -> SExp
- year :: SExp -> SExp
- leftShift :: SExp -> SExp -> SExp
- __NestLevel :: SExp
- __idle :: SExp
- scopeIdentity :: SExp
- unicode :: SExp -> SExp
- originalDbName :: SExp
- ltrim :: SExp -> SExp
- appName :: SExp
- sysDateTime :: SExp
- nodeIdFromParts :: SExp -> SExp -> SExp
- dateFromParts :: SExp -> SExp -> SExp -> SExp
- __spid :: SExp
- version :: SExp
- fulltextserviceProperty :: SExp -> SExp
- isObjectSigned :: SExp -> SExp -> SExp -> SExp -> SExp
- datepart :: SExp -> SExp -> SExp
- systemUser :: SExp
- newsequentialid :: SExp
- bitCount :: SExp -> SExp
- minActiveRowVersion :: SExp
- fileName :: SExp -> SExp
- colLength :: SExp -> SExp -> SExp
- indexKeyProperty :: SExp -> SExp -> SExp -> SExp -> SExp
- errorMessage :: SExp
- getFilestreamTransactionContext :: SExp
- __fetchStatus :: SExp
- errorLine :: SExp
- __totalWrite :: SExp
- hashBytes_MD2 :: SExp -> SExp
- hashBytes_MD4 :: SExp -> SExp
- hashBytes_MD5 :: SExp -> SExp
- hashBytes_SHA :: SExp -> SExp
- hashBytes_SHA1 :: SExp -> SExp
- hashBytes_SHA2_256 :: SExp -> SExp
- hashBytes_SHA2_512 :: SExp -> SExp
- datediffBig :: SExp -> SExp -> SExp -> SExp
- __packetErrors :: SExp
- sysDateTimeOffset :: SExp
- degrees :: SExp -> SExp
- getUtcDate :: SExp
- sqlVariantProperty :: SExp -> SExp -> SExp
- connectionProperty :: SExp -> SExp
- __langid :: SExp
- __cursorRows :: SExp
- translate :: SExp -> SExp -> SExp -> SExp
- dateTrunc :: SExp -> SExp -> SExp
- approxCountDistinct :: SExp -> SExp
- verifySignedByAsymKey :: SExp -> SExp -> SExp -> SExp
- jsonValue :: SExp -> SExp -> SExp
- applockMode :: SExp -> SExp -> SExp -> SExp
- right :: SExp -> SExp -> SExp
- certProperty_EXPIRY_DATE :: SExp -> SExp
- certProperty_START_DATE :: SExp -> SExp
- certProperty_ISSUER_NAME :: SExp -> SExp
- certProperty_CERT_SERIAL_NUMBER :: SExp -> SExp
- certProperty_SUBJECT :: SExp -> SExp
- certProperty_SID :: SExp -> SExp
- certProperty_STRING_SID :: SExp -> SExp
- currentTimeStamp :: SExp
- len :: SExp -> SExp
- isDate :: SExp -> SExp
- stdevp :: Maybe Distinctness -> SExp -> SExp
- parse :: SExp -> SExp -> SExp
- parse_USING :: SExp -> SExp -> SExp -> SExp
- applockTest :: SExp -> SExp -> SExp -> SExp -> SExp
- log10 :: SExp -> SExp
- statsDate :: SExp -> SExp -> SExp
- typeProperty :: SExp -> SExp -> SExp
- dateTimeOffsetFromParts :: SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp -> SExp
- serverProperty :: SExp -> SExp
- stringAgg :: SExp -> SExp -> SExp
- stringAgg_WITHIN_GROUP_ORDER_BY :: SExp -> SExp -> SExp -> Maybe OrderDir -> SExp
- keyGuid :: SExp -> SExp
- encryptByCert :: SExp -> SExp -> SExp
- asin :: SExp -> SExp
- indexProperty :: SExp -> SExp -> SExp -> SExp
- objectDefinition :: SExp -> SExp
- xactState :: SExp
- sysUtcDateTime :: SExp
- binaryChecksum_STAR :: SExp
- binaryChecksum :: NonEmpty SExp -> SExp
- cos :: SExp -> SExp
- choose :: SExp -> SExp -> NonEmpty SExp -> SExp
- left :: SExp -> SExp -> SExp
- publishingserverName :: SExp
- graphIdFromNodeId :: SExp -> SExp
- hasDbaccess :: SExp -> SExp
- databasePropertyex :: SExp -> SExp -> SExp
- objectProperty :: SExp -> SExp -> SExp
- greatest :: NonEmpty SExp -> SExp
- colName :: SExp -> SExp -> SExp
- parseName :: SExp -> SExp -> SExp
- power :: SExp -> SExp -> SExp
- decompress :: SExp -> SExp
- eventdata :: SExp
- sessionProperty :: SExp -> SExp
- __Timeticks :: SExp
- __ioBusy :: SExp
- checksumAgg :: Maybe Distinctness -> SExp -> SExp
- upper :: SExp -> SExp
- fileGroupName :: SExp -> SExp
- ceiling :: SExp -> SExp
- textvalid :: SExp -> SExp -> SExp -> SExp -> SExp
- sessionId :: SExp
- isNumeric :: SExp -> SExp
- __tranCount :: SExp
- tryParse :: SExp -> SExp -> SExp
- tryParse_USING :: SExp -> SExp -> SExp -> SExp
- __remserver :: SExp
- floor :: SExp -> SExp
- least :: NonEmpty SExp -> SExp
- sessionContext :: SExp -> SExp
- stringEscape :: SExp -> SExp -> SExp
- stdev :: Maybe Distinctness -> SExp -> SExp
- nChar :: SExp -> SExp
- __totalErrors :: SExp
- fulltextcatalogProperty :: SExp -> SExp -> SExp
- space :: SExp -> SExp
- toDateTimeOffset :: SExp -> SExp -> SExp
- asymKeyId :: SExp -> SExp
- fileGroupProperty :: SExp -> SExp -> SExp
- grouping :: SExp -> SExp
- currentTimeZoneId :: SExp
- atn2 :: SExp -> SExp -> SExp
- encryptByAsymKey :: SExp -> SExp -> SExp
- month :: SExp -> SExp
- user :: SExp
- rtrim :: SExp -> SExp
- __maxPrecision :: SExp
- radians :: SExp -> SExp
- __Datefirst :: SExp
- databasePrincipalId :: SExp -> SExp
- switchOffset :: SExp -> SExp -> SExp
- soundex :: SExp -> SExp
- objectIdFromEdgeId :: SExp -> SExp
- objectIdFromNodeId :: SExp -> SExp
- hostId :: SExp
- dateName :: SExp -> SExp -> SExp
- keyId :: SExp -> SExp
- rowCountBig :: SExp
- hostName :: SExp
- msaVarp :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaVarp_ALL :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaVar :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaVar_ALL :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaCountBig :: SExp -> Maybe PartitionBy -> SExp
- msaCountBig_STAR :: Maybe PartitionBy -> SExp
- msaCountBig_ALL :: SExp -> Maybe PartitionBy -> SExp
- msaCountBig_ALL_STAR :: Maybe PartitionBy -> SExp
- msaMax :: SExp -> PartitionBy -> Maybe OverOrderBy -> SExp
- msaMax_ALL :: SExp -> PartitionBy -> Maybe OverOrderBy -> SExp
- msaStdevp :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaStdevp_ALL :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaStdev :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaStdev_ALL :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaMin :: SExp -> Maybe PartitionBy -> Maybe OverOrderBy -> SExp
- msaMin_ALL :: SExp -> Maybe PartitionBy -> Maybe OverOrderBy -> SExp
- msaSum :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaSum_ALL :: SExp -> Maybe PartitionBy -> OverOrderBy -> SExp
- msaCount :: SExp -> Maybe PartitionBy -> SExp
- msaCount_STAR :: Maybe PartitionBy -> SExp
- msaCount_ALL :: SExp -> Maybe PartitionBy -> SExp
- msaCount_ALL_STAR :: Maybe PartitionBy -> SExp
Documentation
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');
:: 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_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');
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;
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;
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;
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;
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;
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;
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);
:: 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;
:: 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;
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;
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;
:: 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;
:: 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;
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
:: 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;
:: 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;
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');
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');
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
decryptByPassPhrase_AddAuthenticator_Authenticator #
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
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) ;
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) ;
:: SExp | |
-> Maybe PartitionBy | |
-> OverOrderBy | overorderby |
-> SExp |
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;
:: 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;
:: 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;
:: 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;
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);
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);
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
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
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
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
:: 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;
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
decryptByKeyAutoAsymKey_AddAuthenticator #
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_AddAuthenticator_Authenticator #
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
asymKeyProperty_KeyId_AlgorithmDesc #
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
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
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
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
encryptByPassPhrase_AddAuthenticator_Authenticator #
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
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;
decryptByKeyAutoCert_AddAuthenticator #
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_AddAuthenticator_Authenticator #
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;
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)
triggerNestLevel_TriggerType #
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_TriggerType_TriggerEventCategory #
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)
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_ObjectId_TriggerType #
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_TriggerType_TriggerEventCategory #
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)
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);
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);
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;
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;
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
decryptByAsymKey_AsymKeyPassword #
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
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
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
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
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
:: 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;
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
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
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));
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));
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));
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));
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
decryptByKey_AddAuthenticator_Authenticator #
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
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;
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;
:: SExp | |
-> Maybe PartitionBy | |
-> OverOrderBy | overorderby |
-> SExp |
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;
:: 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;
:: 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;
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');
certprivateKey_DecryptionPassword #
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');
:: 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;
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');
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');
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
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
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');
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_SubSecurable_SubSecurableClass #
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');
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;
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;
:: [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;
symKeyProperty_KeyId_AlgorithmDesc #
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
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
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
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.';
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.';
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.';
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)
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)
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);
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);
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.
:: 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_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.
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
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
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');
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');
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] ;
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] ;
:: [(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;
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';
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';
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_DatabaseName_ObjectType #
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_SchemaName #
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_SchemaName_ObjectType #
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';
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_SchemaName_ObjectType #
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';
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
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
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
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
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;
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
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
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
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
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
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
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);
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);
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
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
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
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
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
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
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
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');
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');
Origin documentation for suserName
Syntax:
SUSER_NAME ( [ server_user_id ] )
Returns the login identification name of the user.
Example:
SELECT SUSER_NAME(1);
Origin documentation for suserName_ServerUserId
Syntax:
SUSER_NAME ( [ server_user_id ] )
Returns the login identification name of the user.
Example:
SELECT SUSER_NAME(1);
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
encryptByKey_AddAuthenticator_Authenticator #
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
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
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_DatabaseName_SchemaName #
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
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
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');
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');
:: 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;
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
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
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
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
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');
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');
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);
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);
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;
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.';
isRoleMember_DatabasePrincipal #
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.';
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 ;
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 ;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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
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;
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
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
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);
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 );
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;
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;
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
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
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');
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);
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;
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
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%';
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
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();
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';
__language :: SExp #
Origin documentation for __language
Syntax:
@@LANGUAGE
Returns the name of the language currently being used.
Example:
SELECT @@LANGUAGE AS 'Language Name';
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);
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; ;
__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';
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;
__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
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;
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' ;
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;
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
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
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
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
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;
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.
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);
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
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
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)
Syntax:
TAN ( float_expression )
Returns the tangent of the input expression.
Example:
SELECT TAN(PI()/2);
Example:
SELECT TAN(.45);
__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';
__serverName :: SExp #
Origin documentation for __serverName
Syntax:
@@SERVERNAME
No description
Example:
SELECT @@SERVERNAME AS 'Server Name'
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
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
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
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];
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;
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
__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';
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;
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
Origin documentation for currentRequestId
Syntax:
CURRENT_REQUEST_ID()
This function returns the ID of the current request within the current session.
:: 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;
:: 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;
__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'
__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';
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);
Origin documentation for certId
Syntax:
CERT_ID ( 'cert_name' )
This function returns the ID value of a certificate.
Example:
SELECT Cert_ID('ABerglundCert3'); GO
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
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;
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.*/
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
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
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
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;
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
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 */
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
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
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
__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';
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');
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
__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
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
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;
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;
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
__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
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
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;
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';
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
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
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
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));
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
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());
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
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';
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
:: Maybe Distinctness | |
-> SExp | expression |
-> SExp |
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;
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);
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);
__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
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';
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
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;
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.
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.');
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
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();
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; ;
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;
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';
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();
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
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?] ;
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
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;
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()));
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;
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
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
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;
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];
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
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) .
__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
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
__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'
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;
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;
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;
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;
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;
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;
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;
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
__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';
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()];
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
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 */
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');
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';
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'
__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
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;
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);
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;
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
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') )
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
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);
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
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
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_CERT_SERIAL_NUMBER #
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
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
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
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
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;
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';
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';
:: 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;
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;
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;
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
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);
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
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');
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
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
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
stringAgg_WITHIN_GROUP_ORDER_BY #
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
Origin documentation for keyGuid
Syntax:
Key_GUID( 'Key_Name' )
Returns the GUID of a symmetric key in the database.
Example:
SELECT Key_GUID('ABerglundKey1');
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
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;
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
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
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
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'
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
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
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;
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;
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;
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.
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;
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
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');
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
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
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;
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
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);
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)) );
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
Origin documentation for sessionProperty
Syntax:
SESSIONPROPERTY (option)
Returns the SET options settings of a session.
Example:
SELECT SESSIONPROPERTY ('CONCAT_NULL_YIELDS_NULL')
__Timeticks :: SExp #
Origin documentation for __Timeticks
Syntax:
@@TIMETICKS
Returns the number of microseconds per tick.
Example:
SELECT @@TIMETICKS AS 'Time Ticks';
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';
:: 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;
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;
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
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
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
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();
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
__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
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;
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;
__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;
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);
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
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');
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;
:: 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;
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
__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';
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
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
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
Origin documentation for asymKeyId
Syntax:
ASYMKEY_ID ( 'Asym_Key_Name' )
Returns the ID of an asymmetric key.
Example:
SELECT ASYMKEY_ID('ABerglundKey11'); GO
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
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
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 */
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
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
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;
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
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.');
__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'
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
__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;
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
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
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
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;
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;
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
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');
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');
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 .
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
:: 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;
:: 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;
:: 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;
:: 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;
:: 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.
:: 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.
:: 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.
:: 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.
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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;
:: 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');
:: 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');
:: 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');
:: 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');