sandragaw.files.wordpress.com€¦  · web viewusing the > comparison operator as an example,...

27
1. CREATE DATABASE OBJECTS | 24% *CREATE/ALTER/DROP DATABASE CREATE A DATABASE TO THE DEFAULT LOCATION CREATE DATABASE DatabaseName For additional options, see: https://msdn.micro soft.com/en-us/library/ms186312.aspx DROP A DATABASE DROP DATABASE DatabaseName https://msdn.microsoft.com/en-us/library/ms177419.aspx ALTER A DATABASE ALTER DATABASE DatabaseName --Argument Modify Name = NewDatabaseName https://msdn.microsoft.com/en-us/library/ms174269.aspx *CREATE/ALTER/DROP TABLE - ADD/DROP/RENAME TABLE’S COLUMNS, CREATE TABLE CREATE TABLE TableName ( column1 varchar(255) NOT NULL, column2 int NULL, column3 varchar(max) ,....) https://msdn.microsoft.com/en-us/library/ms174979.aspx *If nullability is not defined, NULL is the default. ALTER TABLE ADD A COLUMN ALTER TABLE TableName ADD column4 datetime https://msdn.microsoft.com/en-us/library/ms190238.aspx DROP COLUMN ALTER TABLE TableName DROP COLUMN column4 DROP TABLE DROP TABLE TableName RENAME COLUMN EXEC sp_rename 'dbo.TableName.column1', 'NewColumn1', 'Column' EXEC sp_rename [schema.tablename.columnname], [NewColumnName], [object you are renaming] https://msdn.microsoft.com/en-us/library/ms188351.aspx *DATA TYPES COMMON

Upload: voxuyen

Post on 04-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

1. CREATE DATABASE OBJECTS | 24%

*CREATE/ALTER/DROP DATABASE

CREATE A DATABASE TO THE DEFAULT LOCATIONCREATE DATABASE DatabaseName

For additional options, see:

https://msdn.micro soft.com/en-us/library/ms186312.aspx

DROP A DATABASEDROP DATABASE DatabaseName

https://msdn.microsoft.com/en-us/library/ms177419.aspx

ALTER A DATABASEALTER DATABASE DatabaseName

--ArgumentModify Name = NewDatabaseName

https://msdn.microsoft.com/en-us/library/ms174269.aspx

*CREATE/ALTER/DROP TABLE - ADD/DROP/RENAME TABLE’S COLUMNS,

CREATE TABLECREATE TABLE TableName (

column1 varchar(255) NOT NULL,column2 int NULL,column3 varchar(max),....)

https://msdn.microsoft.com/en-us/library/ms174979.aspx

*If nullability is not defined, NULL is the default.ALTER TABLEADD A COLUMNALTER TABLE TableName

ADD column4 datetimehttps://msdn.microsoft.com/en-us/library/ms190238.aspx

DROP COLUMNALTER TABLE TableName

DROP COLUMN column4DROP TABLEDROP TABLE TableName

RENAME COLUMNEXEC sp_rename 'dbo.TableName.column1', 'NewColumn1', 'Column'EXEC sp_rename [schema.tablename.columnname], [NewColumnName], [object you are renaming]

https://msdn.microsoft.com/en-us/library/ms188351.aspx

*DATA TYPES

COMMONINT Used for numbers. The int data type is the

primary integer data type in SQL Server. DECIMAL (p,s) Fixed precision and scale numbers. For

instance, DECIMAL (10,4) will allow for 10 total numbers (left and right of the decimal) with a max of 4 to the right of the decimal.

MONEY Data types that represent monetary or currency values.

DATETIME Defines a date that is combined with a time of day with fractional seconds that is based on a 24-hour clock.

DATE Defines a date.CHAR (n) Fixed-length, non-Unicode string

data. n defines the string length and must be a value from 1 through 8,000. For instance CHAR(2) allows for 2 letters.

VARCHAR(n) Variable-length, non-Unicode string data. n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size.

https://msdn.microsoft.com/en-us/library/ms187752.aspx

DATETIME ADVANCEDDATE Defines a date. 2016-10-17TIME 11:16:32.3030000DATETIME Defines a date that is

combined with a time of day with fractional seconds that is based on a 24-hour clock.

2016-10-17 11:16:32.303

DATETIME2 Uses a larger default fractional precision than datetime

2016-10-17 11:16:32.3030000

DATETIMEOFFSET Defines a date that is combined with a time of a day that has time zone awareness and is based on a 24-hour clock. It contains an offset that indicates how much that value differs from UTC

2016-10-17 11:16:32.3030000 +00:00

SMALLDATETIME 2016-10-17 11:17:00

XMLThe xml data type stores xml data rather than as a separate xml file

SPACIAL GEOMETRY supports planar (flat-earth) data GEOGRAPHY stores ellipsoidal (round-earth) data such as latitude and longitude coordinates

https://msdn.microsoft.com/en-us/library/bb964711.aspx

*CONSTRAINTS

PRIMARY KEYA primary key is a unique, non-null identifier. Defining a column as a primary key will automatically create a clustered index on that key. When there is more than one primary key in a table, it is referred to as a Composite Key

https://msdn.microsoft.com/en-us/library/ms189039.aspx CREATE PRIMARY KEY ON TABLE CREATIONMETHOD 1

CREATE TABLE TableName (column1 varchar(255) PRIMARY KEY,column2 int,column3 varchar(max))

METHOD 2

CREATE TABLE TableName (column1 varchar(255),column2 int,column3 varchar(max),CONSTRAINT constraintName PRIMARY KEY (column1, column2))

ADD PRIMARY KEY AFTER TABLE CREATION

ALTER TABLE TableNameADD PRIMARY KEY (Column1)

ALTER TABLE TableNameADD CONSTRAINT constraintName PRIMARY KEY (column1, column2)

* If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).

 UNIQUE KEYThe unique constraint requires unique values and allows for one of those values to be NULL. By default it adds a UNIQUE non-clustered index

CREATE TABLE TableName (column1 varchar(255) UNIQUE,column2 int,column3 varchar(max))

ALTER TABLE TableNameADD UNIQUE (Column1)

https://msdn.microsoft.com/en-us/library/ms190024.aspx FOREIGN KEYA foreign key in one table links a primary key in another table. For instance, in the example below, the customerID field in the CustomerAddress2 table links to the customerID field in the Customer table

METHOD 1CREATE TABLE [SalesLT].[CustomerAddress2](

[CustomerID] [int] NOT NULL,[AddressID] [int] NOT NULL,[AddressType] [dbo].[Name] NOT NULL,[ModifiedDate] [datetime] NOT NULLPRIMARY KEY (AddressID),FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID_))

METHOD 2

ALTER TABLE CustomerAddress2ADD FOREIGN KEY (CustomerID)REFERENCES Customer(CustomerID)

https://msdn.microsoft.com/en-us/library/ms189049.aspx

CHECKThe check constraint specifies the data values that are acceptable.

CREATE TABLE ADDRESS(AddressID int,City varchar(255),State varchar(2) NOT NULL CHECK (State IN ('FL', 'GA', 'LA')),Street varchar(255))

ALTER TABLE ADDRESSADD State varchar(2) NOT NULLCONSTRAINT CHK_StateCHECK (State IN ('FL', 'GA', 'LA'))

https://msdn.microsoft.com/en-us/library/ms190377.aspx

DEFAULTDefault constraint sets a default value for a column. This value can be changed.

CREATE TABLE ADDRESS(AddressID int,City varchar(255),State varchar(2) NOT NULL DEFAULT 'FL',Street varchar(255))

ALTER TABLE ADDRESSALTER COLUMN [STATE] SET DEFAULT 'FL'

https://msdn.microsoft.com/en-us/library/ms187872.aspx

*COMPUTED COLUMNS

Computed columns are columns in a table that do not hold static values, but rather values derived from other columns, calculations, or a combination of both. A computed column cannot be used as a DEFAULT or FOREIGN KEY constraint definition or with a NOT NULL constraint definition. CREATE TABLE SalesOrder

(OrderID int,ItemNumber int,OrderQty int,UnitPrice money,LineTotal AS OrderQty*UnitPrice)

ALTER TABLE SalesOrderADD TotalWithTax as OrderQty*UnitPrice*1.07

https://msdn.microsoft.com/en-us/library/ms188300.aspx PERSITED COMPUTED COLUMNSpecifying that a computed column be PERSITED requires more storage space in that the column is no longer simply a virtual column that is computed each time a query is run. The computed value persists in the table and is re-calculated as necessary.

CREATE TABLE SalesOrder(OrderID int,ItemNumber int,OrderQty int,UnitPrice money,LineTotal AS OrderQty*UnitPrice PERSISTED)

*VIEWS

A view is a saved query or a virtual table.

CREATE VIEW NameOnly ASSELECT Title, FirstName, MiddleName, LastNameFROM [AdventureWorksLT2008].[SalesLT].[Customer]WHERE MiddleName is not NULL

SELECT *FROM NameOnly

https://msdn.microsoft.com/en-us/library/ms187956.aspx

OPTIONAL ARGUMENTSWITH CHECK OPTIONUpdate statements can be run against views to update the data in the underlying tables. The CHECK OPTION blocks you from making changes to a table using the view that would result in that record no longer appearing in the view. For instance, in the example below, if I attempt use the view to update the underlying Customer table by setting any of the customer’s middle names to a NULL value, it will produce an error because the view would no longer return that record. I can however use the view to change anyone’s middle initial.

CREATE VIEW NameOnly ASSELECT Title, FirstName, MiddleName, LastNameFROM [AdventureWorksLT2008].[SalesLT].[Customer]WHERE MiddleName is not NULLWITH CHECK OPTION

--Will not work because the view only displays records who's MiddleName values are not NULLUPDATE NameOnly

SET MiddleName= NULLWHERE FirstName='Orlando' and LastName='Gee'

--This will workUPDATE NameOnly

SET MiddleName= 'N.'WHERE FirstName='Orlando' and LastName='Gee'

WITH ENCRYPTIONBlocks others from seeing the definition of the view (the select statement the view uses).

WITH SCHEMABINDINGBinds the view to the schema of the underlying table or tables. This means that no changes can be made to the underlying table structure that would affect the view. For example, if the column MiddleName was included in the view select statement, the MiddleName column could not be dropped from the Customer table until either the view was dropped or the view was modified.

WITH VIEW_METADATAAllows third party applications, such as those developed in C# or VB.NET to retrieve details regarding the structure of the view. It will not however, reveal the base table names.

*MODIFY/DELETE A VIEW

Views are modified by using the ALTER VIEW ViewName statement followed by and update SELECT statement.

ALTER VIEW NameOnly ASSELECT Title, FirstName, LastNameFROM [AdventureWorksLT2008].[SalesLT].[Customer]

WHERE MiddleName is not NULL

Views are deleted by using the DROP VIEW ViewName statement.

DROP VIEW NameOnly

https://msdn.microsoft.com/en-us/library/ms173846.aspx

*INDEXED VIEWS

View must be created with WITH SCHEMABINDING OPTION View can only reference tables If GROUP BY is present, the VIEW definition must contain COUNT_BIG(*) and must not contain

HAVING If the view definition contains a GROUP BY clause, the key of the unique clustered index can

reference only the columns specified in the GROUP BY clause.CREATE UNIQUE CLUSTERED INDEX IDX_V1 ON Sales.vOrders (OrderDate, ProductID);

https://msdn.microsoft.com/en-us/library/ms191432.aspx

*STORED PROCEDURES

A stored procedure is prepared sql code that can be re-run. For instance, if every month you increase the price of all products with over 100 units on hand by 5%, you can simply type EXECUTE RaisePrices rather than re-writing the update command monthly.

CREATE PROCEDURE RaisePrices ASUPDATE PRODUCTSSET PRICE= PRICE*1.05WHERE UnitsOnHand > 100

EXECUTE RaisePriceshttps://msdn.microsoft.com/en-us/library/ms345415.aspx

ADDING PARAMETERS TO PROCEDURESSuppose that the max number of UnitsOnHand varies by month. You can parametrize that value rather than alter the procedure. When you execute the stored procedure, you simply add the value to the end of the string.

CREATE PROCEDURE RaisePrices @UnitMax intASUPDATE PRODUCTSSET PRICE= PRICE*1.05WHERE UnitsOnHand > @UnitMax

EXECUTE RaisePrices '200'

TO MODIFYTo modify a stored procedure, use the ALTER PROCEDURE statement and re-write the command.

ALTER PROCEDURE RaisePrices ASUPDATE PRODUCTSSET PRICE= PRICE*1.05WHERE UnitsOnHand > 200

TO DELETE A PROCEDURETo delete a stored procedure, use the DROP statement

DROP PROCEDURE RaisePrices

*DML TRIGGERS (INSERTED, UPDATED, UPDATE FUNCTION) VS CHECK CONSTRAINT

Inserted and deleted tables; nested triggers; types of triggers; update functions; handle multiple rows in a session; performance implications of triggers

TRIGGER ON AN INSERT, UPDATE, OR DELETE STATEMENT TO A TABLE OR VIEW (DML TRIGGER)CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name

* NATIVE_COMPILATION- Indicates that the trigger is natively compiled. This option is required for triggers on memory-optimized tables.*SCHEMABINDING- Ensures that tables that are referenced by a trigger cannot be dropped or altered. This option is required for triggers on memory-optimized tables and is not supported for triggers on traditional tables.

CREATE TRIGGER reminder1 ON Sales.Customer AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10); GO

TRIGGER ON A CREATE, ALTER, DROP, GRANT, DENY, REVOKE, OR UPDATE STATISTICS STATEMENT (DDL TRIGGER)

CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH <ddl_trigger_option> [ ,...n ] ] { FOR | AFTER } { event_type | event_group } [ ,...n ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] } <ddl_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ]

CREATE TRIGGER ddl_trig_database ON ALL SERVER FOR CREATE_DATABASE AS

PRINT 'Database Created.' SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)

[1]','nvarchar(max)') GO

TRIGGER ON A LOGON EVENT (LOGON TRIGGER) CREATE TRIGGER trigger_name ON ALL SERVER [ WITH <logon_trigger_option> [ ,...n ] ]

{ FOR| AFTER } LOGON AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] } <logon_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ]

STRING FUNCTIONS

String functions are built in functions that perform an operation a string input value and return a string or numeric value. Examples:

ASCII LTRIM SOUNDEXCHAR NCHAR SPACECHARINDEX PATINDEX STRCONCAT QUOTENAM

ESTRING_ESCAPE

DIFFERENCE

REPLACE STRING_SPLIT

FORMAT REPLICATE STUFFLEFT REVERSE SUBSTRINGLEN RIGHT UNICODELOWER RTRIM UPPER

CONCAT ( string_value1, string_value2 [, string_valueN ] ) SUBSTRING ( expression ,start , length ) REPLACE ( string_expression , string_pattern , string_replacement ) LEN ( string_expression ) STRING_SPLIT ( string , separator ) STR ( float_expression [ , length [ , decimal ] ] ) FORMAT (value, format, culture)

https://msdn.microsoft.com/en-us/library/ms181984.aspx

USER DEFINED FUNCTIONS

User defined functions can be scalar value or table value. They are similar to stored procedures in that they are saved code, but functions can be nested in queries.

SCALAR FUNCTIONS

CREATE FUNCTION CalculateAge (@Birthday DATETIME)RETURNS intASBEGIN

DECLARE @AGE INTSELECT @AGE = DATEDIFF(YY, @Birthday,GETDATE())RETURN @AGE;

END;

SELECT dbo.CalculateAge('01/08/2000')

CREATE FUNCTION CalculateOrderAge (@OrderDate DATETIME)RETURNS intASBEGIN

DECLARE @AGE INT

SELECT @AGE = DATEDIFF(YY, @OrderDate,GETDATE())RETURN @AGE;

END;

SELECT SalesOrderID, dbo.CalculateOrderAge(OrderDate) as OrderAgeFROM SalesLT.SalesOrderHeader

SP VS UDF

Sl. No.

User Defined function Stored Procedure

1 Function must return a value. Stored procedure may or not return values.2 Will allow only Select statement, it

will not allow us to use DML statements.

Can have select statements as well as DML statements such as insert, update, delete

etc3 It will allow only input parameters,

doesn’t support output parameters.It can have both input and output parameters.

4 It will not allow us to use try-catch blocks.

For exception handling we can use try catch blocks.

5 Transactions are not allowed within functions.

Can use transactions within Stored procefures.

6 We can use only table variables, it will not allow using temporary tables.

Can use both table variables aswell as temporary table in it.

7 Stored procedures can’t be called from function.

Stored Procedures can call functions.

8 Functions can be called from select statement.

Procedures can’t be called from Select/Where/Having etc statements. Execute/Exec

statement can be used to call/execute stored procedure.

9 UDF can be used in join clause as a result set.

Procedures can’t be used in Join clause

http://sqlhints.com/2012/06/16/difference-between-stored-procedure-and-user-defined-function-in-sql-server/

2. WORK WITH DATA | 27%

USE THE RANKING FUNCTION TO SELECT TOP(X) ROWS FOR MULTIPLE CATEGORIES IN A SINGLE QUERY- RANKING FUNCTIONS (ROW_NUMBER, RANK, DENSE_RANK, NTILE).

RANK RANK () OVER (PARTITION BY columns ORDER BY columns)

ROW_NUMBER

Has gaps in case of duplicatesValue Rank5 110 210 215 4

ROW_NUMBER () OVER (PARTITION BY columns ORDER BY columns) as RN

DENSE_RANK

No gaps in case of duplicates Value Rank5 1

DENSE_RANK () OVER (PARTITION BY columns ORDER BY columns)

10 210 215 3

NTILEproductid

Linetotal Quartile

973 1020.594000 1999 971.982000 1998 647.988000 2875 56.209076 2938 48.588000 3711 20.994000 3874 10.788000 4

NTILE (#) OVER(ORDER BY columns)

WRITE AND PERFORM QUERIES EFFICIENTLY USING CODE ITEMS SUCH AS SYNONYMS, AND JOINS (EXCEPT, INTERSECT)

SYNONYMS--Create to avoid typing schema nameCREATE SYNONYM SalesAddressFOR SalesLT.Address

--Create to avoid typing four part nameCREATE SYNONYM GISAddressFOR [MyGisServer/GIS].GIS.Address.Saleshttps://msdn.microsoft.com/en-us/library/ms187552.aspx

EXCEPT AND INTERSECTReturns distinct rows by comparing the results of two queries.EXCEPT returns distinct rows from the left input query that aren’t output by the right input query.INTERSECT returns distinct rows that are output by both the left and right input queries operator.The basic rules for combining the result sets of two queries that use EXCEPT or INTERSECT are the following:

The number and the order of the columns must be the same in all queries. The data types must be compatible.

SELECT COL1, COL2, COL3FROM TABLE1

EXCEPT

SELECT COL1, COL2, COL3FROM TABLE2

https://msdn.microsoft.com/en-us/library/ms188055.aspx

*IMPLEMENT LOGIC WHICH USES DYNAMIC SQL AND SYSTEM METADATA

INFORMATION SCHEMA VIEWS

CHECK_CONSTRAINTS REFERENTIAL_CONSTRAINTS

COLUMN_DOMAIN_USAGE ROUTINESCOLUMN_PRIVILEGES ROUTINE_COLUMNS

COLUMNS SCHEMATACONSTRAINT_COLUMN_USAGE

TABLE_CONSTRAINTS

CONSTRAINT_TABLE_USAGE TABLE_PRIVILEGESDOMAIN_CONSTRAINTS TABLESDOMAINS VIEW_COLUMN_USAGEKEY_COLUMN_USAGE VIEW_TABLE_USAGEPARAMETERS VIEWS

*ROUTINES: Returns one row for each stored procedure and function that can be accessed by the current user in the current databaseselect * from information_schema.columns

https://msdn.microsoft.com/en-us/library/ms186778.aspx

NEW FUNCTIONS IN SQL SERVER 2012 (IFF, TRY_PARSE, CONCAT, FORMAT)

TRY_CONVERTReturns NULL instead of error if data cannot be converted.

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

PARSE / TRY_PARSEIncludes a culture clause in a conversion

PARSE ( string_value AS data_type [ USING culture ] ) EOMONTHReturns End of month date

select EOMONTH(getdate())

DATEFROMPARTSSELECT

DATEFROMPARTS(2012, 02, 12)

AS DATE_FROMPARTS,

DATETIME2FROMPARTS(2012, 02, 12, 13, 30, 5, 1, 7)

AS DATETIME2_FROMPARTS,

DATETIMEFROMPARTS(2012, 02, 12, 13, 30, 5, 997)

AS DATETIME_FROMPARTS,

DATETIMEOFFSETFROMPARTS(2012, 02, 12, 13, 30, 5, 1, -8, 0, 7)

AS DATETIMEOFFSET_FROMPARTS,

SMALLDATETIMEFROMPARTS(2012, 02, 12, 13, 30)

AS SMALLDATETIME_FROMPARTS,

TIMEFROMPARTS(13, 30, 5, 1, 7)

AS TIME_FROMPARTS;

DATE_FROMPARTS DATETIME2_FROMPARTS DATETIME_FROMPARTS2012-02-12 2012-02-12 13:30:05.0000001 2012-02-12 13:30:05.997

DATETIMEOFFSET_FROMPARTS SMALLDATETIME_FROMPARTS TIME_FROMPARTS2012-02-12 13:30:05.0000001 -08:00

2012-02-12 13:30:00 13:30:05.0000001

CHOOSE

CHOOSE (index, val_1, val_2 [, val_n ] )

CHOOSE(3, ‘A’, ‘B’, ‘C’, D’) will return C

SELECT JobTitle, HireDate, CHOOSE(MONTH(HireDate),'Winter','Winter', 'Spring','Spring','Spring','Summer','Summer', 'Summer','Autumn','Autumn','Autumn','Winter') AS Quarter_Hired FROM HumanResources.Employee WHERE YEAR(HireDate) > 2005 ORDER BY YEAR(HireDate); https://msdn.microsoft.com/en-us/library/hh213019.aspx

IIFIIF ( boolean_expression, true_value, false_value ) CONCATCONCAT ( string_value1, string_value2 [, string_valueN ] ) FORMATFORMAT ( value, format [, culture ] ) SELECT FORMAT ( GETDATE(), 'd', 'en-US' ) AS 'US English Result' FORMAT VS PARSEPARSE and FORMAT are opposite operations (PARSE converts a string to another type; FORMAT converts a non-string type to a string using a specific format (e.g. currency, date-time).

SELECT FORMAT ( GETDATE(), 'd', 'en-US' ) AS 'US English Result' ,FORMAT ( GETDATE(), 'd', 'en-gb' ) AS 'Great Britain English Result'

SELECT PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-US') AS USResult,PARSE('Monday, 13 December 2010' AS datetime2 USING 'en-gb') AS EnglandResult;

LOG

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

LOG ( float_expression [, base ] ) https://msdn.microsoft.com/en-us/library/ms190319.aspx

*http://sqlmag.com/blog/sql-server-2012-t-sql-glance-new-and-enhanced-functions

ALL TYPES OF JOINS VERSUS THE USE OF DERIVED TABLES;

USE AND UNDERSTAND DIFFERENT DATA ACCESS TECHNOLOGIES

?

CASE VERSUS ISNULL VERSUS COALESCE

ISNULL & COALESCE COALESCE & ISNULL both return the first non-null datatype ISNULL takes 2 inputs and coalesce takes more

SELECT COALESCE(@x, @y, @z); SELECT ISNULL(@x, @y);

CASEEvaluates a list of conditions and returns one of multiple possible result expressions.SELECT ProductNumber, Category = CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' END, Name FROM Production.Product ORDER BY ProductNumber;

https://msdn.microsoft.com/en-us/library/ms181765.aspx

*PIVOT AND UNPIVOTSELECT <non-pivoted column>, [first pivoted column] AS <column name>, [second pivoted column] AS <column name>, ... [last pivoted column] AS <column name> FROM (<SELECT query that produces the data>) AS <alias for the source query> PIVOT ( <aggregation function>(<column being aggregated>) FOR [<column that contains the values that will become column headers>] IN ( [first pivoted column], [second pivoted column], ... [last pivoted column]) ) AS <alias for the pivot table> <optional ORDER BY clause>;

https://msdn.microsoft.com/en-us/library/ms177410.aspx

*APPLY OPERATORS (CROSS APPLY VS OUTER APPLY)

Cross apply works like an inner join evaluating the right table first Outer apply works like outer join evaluating the right table first Use apply when second “table” is a function

https://technet.microsoft.com/en-us/library/ms175156(v=sql.105).aspx

IMPACT OF GUID (NEWID, NEWSEQUENTIALID) ON DATABASE PERFORMANCE; SEQUENCE

IDENTITYIdentity only specifies uniqueness within a table. Performs better than uniqueidentifier.

UNIQUEIDENTIFIERProvides uniqueness across a database or across all databases on networked computers using the ROWGUIDCOL property. Performs worse than identity

NEWIDCreates a random GUID

select NEWID() ;

CREATE TABLE cust ( CustomerID uniqueidentifier NOT NULL DEFAULT newid(), ...

NEWSEQUENTIALIDCreates an incremented GUID that is greater than any GUID previously generated by this function on a specified computer since Windows was started.

When a GUID column is used as a row identifier, using NEWSEQUENTIALID can be faster than using the NEWID function because it can take advantage of more cached data pages.  Using NEWSEQUENTIALID also helps to completely fill the data and index pages.

CREATE TABLE cust ( CustomerID uniqueidentifier NOT NULL DEFAULT NEWSEQUENTIALID(), ...

SEQUENCECREATE SEQUENCE CountBy5 AS tinyint START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 5 CYCLE ; GO SELECT NEXT VALUE FOR CountBy5 AS SurveyGroup, Name FROM sys.objects ; GO ROWGUIDCOL1) The UNIQUEIDENTIFIER along with ROWGUIDCOL NEWSEQUENTIALID() is far more efficient than normal UNIQUEIDENTIFIER along with NEWID().

2) The Unique Ids generated with the second approach are sequential in nature, similar to IDENTITY values.

3) There can be max of one ROWGUIDCOL for a table.

4) You can query the table for ROWGUIDCOL. Example: SELECT ROWGUIDCOL FROM MyTablehttps://www.codeproject.com/tips/125526/using-rowguidcol-in-sql-server

SPATIAL AGGREGATES; ROLLUP, CUBE & GROUPING SETS

SPACIAL AGGREGATES Geometry - square Geography - curvature of the earth

ROLLUPRollup generates subtotals and totals. ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected columns. SELECT city, stateprovince, countryregion, count(addressline1) as NumofCustomers FROM [SalesLT].[Address] GROUP BY countryregion, stateprovince, city WITH ROLLUP

**WITH LABELS

SELECT

CASE WHEN (GROUPING(city)=1) THEN 'ALL CITIES' ELSE ISNULL(City, 'UNKNOWN') END AS CITY, CASE WHEN (GROUPING(stateprovince)=1) THEN 'ALL STATES' ELSE ISNULL(stateprovince, 'UNKNOWN') END AS STATE, CASE WHEN (GROUPING(countryregion)=1) THEN 'ALL COUNTRIES' ELSE ISNULL(countryregion, 'UNKNOWN') END AS COUNTRY, COUNT(addressline1) as NumofCustomers FROM [SalesLT].[Address] GROUP BY countryregion, stateprovince, city WITH ROLLUP

CUBE

Adds summary rows for every combination of groups. The cube is a result set that contains a cross tabulation of all the possible combinations of the dimensions. CUBE generates a result set that shows aggregates for all combinations of values in the selected columns.

SAME QUERY AS ABOVE, BUT WITH CUBE

https://technet.microsoft.com/en-us/library/ms189305(v=sql.90).aspx https://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx

GROUPING SETSAllows you to group multiple sets of data without the use of UNION ALL

SELECT productcategoryid, ThumbnailPhotoFileName, COUNT(productid)FROM [AdventureWorksLT2008].[SalesLT].[Product]GROUP BY productcategoryid, ThumbnailPhotoFileName

UNION ALL

SELECT productcategoryid, NULL AS ThumbnailPhotoFileName, COUNT(productid)FROM [AdventureWorksLT2008].[SalesLT].[Product]GROUP BY productcategoryid

UNION ALL

SELECT NULL AS productcategoryid, ThumbnailPhotoFileName, COUNT(productid)FROM [AdventureWorksLT2008].[SalesLT].[Product]GROUP BY ThumbnailPhotoFileName

UNION ALL

SELECT NULL AS productcategoryid, NULL AS ThumbnailPhotoFileName, COUNT(PRODUCTID)FROM [AdventureWorksLT2008].[SalesLT].[Product]

---------------------------------------------------------------------------------

SELECT productcategoryid, ThumbnailPhotoFileName, COUNT(productid)FROM [AdventureWorksLT2008].[SalesLT].[Product]GROUP BY GROUPING SETS ((productcategoryid), (ThumbnailPhotoFileName), ())

http://www.databasejournal.com/features/mssql/using-the-rollup-cube-and-grouping-sets-operators.html https://technet.microsoft.com/en-us/library/bb510427(v=sql.105).aspx

UNDERSTAND XML DATATYPES AND THEIR SCHEMAS AND INTEROP W/, LIMITATIONS AND RESTRICTIONS; IMPLEMENT XML SCHEMAS AND HANDLING OF XML DATA; XML DATA: HOW TO HANDLE IT IN SQL SERVER AND WHEN AND WHEN NOT TO USE IT, INCLUDING XML NAMESPACES; IMPORT AND EXPORT XML; XML INDEXING- FOR XML RAW/AUTO/PATH [ELEMENTS]

XML DATA TYPES Varbinary (max)– supports conversion to xml – recommended for large XML documents that exceed 2GB

Nvarchar(max) – supports conversion to xml – recommended for large XML documents that exceed 2GB Xml – only supports storage up to 2GB – only datatype that supports xml-specific indexing

CREATING XML

**Well formed document has a ROOT element

SELECT Firstname, LastNameFROM Person.Person As PersonFOR XML [AUTO] [RAW], Root ('People'), ELEMENTS

XML Raw - no table name <row Firstname="Joe" Lastname="Smith"/>XML Auto - table name <Person Firstname="Joe" Lastname="Smith"/>Raw Elements - Groups by row <row></row>Auto Elements- Groups by column nameAuto Root adds table name

SELECT ProductID AS [@ID], NameFROM SalesLT.ProductWHERE ProductCategoryID = 5FOR XML PATH ('Product'), ROOT ('Products');

RETRIEVING DATA

declare @xml_text varchar(4000), @handle int

Select @xml_text = '<People><Person FirstName = "Windston" LastName="Smith"/><Person FirstName = "Bjorn" LastName = "Wilde"/></People>'

EXEC sp_xml_preparedocument @handle OUTPUT, @xml_textSelect * from OPENXML(@handle, '/People/Person')WITh (FirstName varchar(50), LastName varchar(50))

exec sp_xml_removedocument @handle

https://msdn.microsoft.com/en-us/library/ms178107.aspxhttp://john.deardurff.com/xml-sql-tutorial/

CURSORS

A CURSOR allows you to execute an operation (query, update, etc) multiple times looping through different values.

PARTS OF THE CURSORDECLARE Defines a new cursorOPEN Opens and populates the cursor by executing the

SELECT statement defined by the cursorFETCH Retrieves a row from the cursorCLOSE Closes the cursorDEALLOCATE Deletes the cursor definition and releases all system

resources associated with the cursor.STRUCTURE

DECLARE @DBNAME VARCHAR(250)DECLARE DB_CURSOR CURSOR FOR

SELECT name FROM master.sys.databases where database_id >4;OPEN DB_CURSOR;FETCH NEXT FROM DB_CURSOR INTO @DBNAME;WHILE @@FETCH_STATUS =0

BEGINSELECT @DBNAMEFETCH NEXT FROM DB_CURSOR INTO @DBNAME;

END

CLOSE DB_CURSOR;DEALLOCATE DB_CURSOR;GO

FETCH The OFFSET-FETCH clause provides you with an option to fetch only a window or page of results from the result set. OFFSET-FETCH can be used only with the ORDER BY clause.

--Means start at row 10 and return next 5

SELECT FirstName + ' ' + LastName FROM saleslt.customer ORDER BY FirstName OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;

SELECT FirstName + ' ' + LastName FROM saleslt.customer ORDER BY FirstName OFFSET 10 ROWS;

ANY, SOME, ALL

Comparison operators that introduce a subquery can be modified by the keywords ALL or ANY. SOME is an ISO standard equivalent for ANY.

Using the > comparison operator as an example, >ALL means greater than every value. In other words, it means greater than the maximum value. For example, >ALL (1, 2, 3) means greater than 3. >ANY means greater than at least one value, that is, greater than the minimum. So >ANY (1, 2, 3) means greater than 1.

=ANY equivalent to IN

SELECT column_names FROM table_name WHERE column_name operator ANY (SELECT column_name FROM table_name WHERE condition)

https://technet.microsoft.com/en-us/library/ms178543(v=sql.105).aspx http://www.dofactory.com/sql/where-any-all

LEAD / LAGProvides the difference. The LEAD statement below shows the difference in Product total from the current year to the next year

LEAD (ProdTotal) OVER (PARTITION BY Category ORDER BY Year) – ProdTotal AS NextYear

LAG (ProdTotal) OVER (PARTITION BY Category ORDER BY Year) – ProdTotal AS PrevYear

3. MODIFY DATA | 24%

STORED PROCEDURE (WITH EXECUTE AS, RECOMPILE)CREATE PROCEDURE ProcedureNameWITH EXECUTE AS 'XX'

AS...

RECOMPILE Indicates that the Database Engine does not cache a query plan for this procedurehttps://msdn.microsoft.com/en-us/library/ms187926.aspx

MERGE STATEMENT (TARGET, SOURCE, WHEN MATCHED, WHEN NOT MATCHED, OUTPUT)MERGE [AS TARGET]USING [AS SOURCE]ON [WHEN MATCHED THEN ][WHEN NOT MATCHED [BY TARGET]THEN ][WHEN NOT MATCHED BY SOURCETHEN ];

EXCEPT VS INTERSECTEXCEPT returns distinct rows from the left input query that aren’t output by the right input query.INTERSECT returns distinct rows that are output by both the left and right input queries operator.The basic rules for combining the result sets of two queries that use EXCEPT or INTERSECT are the following:

The number and the order of the columns must be the same in all queries. The data types must be compatible.

SELECT ProductID FROM Production.Product

INTERSECT

SELECT ProductID FROM Production.WorkOrder ;

UNION VS UNION ALLUnion returns distinct values

Union ALL will return all including duplicates

CREATE FUNCTIONSSCALAR VALUE FUNCTION

CREATE FUNCTION functionName (@date datetime)Returns intWITH EXECUTE AS CALLERAS

BEGINDECLARE @RETURNVALE INT.....RETURN(@RETURNVALE);

END

SELECT functionNAME(GETDATE())

TABLE VALUE FUNCTION

CREATE FUNCTION tableFunction (@idnumber int)RETURNS TABLEASRETURN(

SELECT.....);

SELECT * FROM tableFunction(452)

SCALAR VS TABLE VALUED FUNCTIONS.Scalar Functions: A scalar function accepts any number of parameters and returns one value.

Inline Table-Valued Functions: This type of functions returns a result set, much like a view. However, ,unlike a view,functions can accept parameters. 

USE OF APPLY WITH UDFShttps://www.simple-talk.com/sql/t-sql-programming/sql-server-apply-basics/

VARCHAR(MAX) AND .WRITE()As per MS BOL the new .WRITE clause of the UPDATE DML statement enables partial or full updates and high performance appends to varchar(max), nvarchar(max) and varbinary(max) data type columns.

**.WRITE minimally logs – use for updates

Syntax: .WRITE ( expression, @Offset , @Length )

@Offset NULL appends to end@Offset = 0 appends to beginning@Offset = # appends starting at #

@Length NULL Replaces all to right@Length =0 inserts at the @offset character@Length=# replaces everything for that many characters

-- Create a table containing a VARCHAR(MAX), NVARCHAR(MAX) or VARBINARY(MAX) column:CREATE TABLE CheckWrite (empID INT, eName VARCHAR(50), descr VARCHAR(MAX)) -- Insert test data in the table:INSERT INTO CheckWriteSELECT 101, 'Manoj Pandey', 'Manoj Pandey is a Sr. SQL Server developer.' -- Check inserted record before UPDATE:SELECT * FROM CheckWrite -- Now UPDATE the descr column by using .WRITE clause:UPDATE CheckWriteSET descr .WRITE('Senior', 18, 3)WHERE empID = 101

https://sqlwithmanoj.com/2011/10/04/update-statement-with-new-write-clause/

4. TROUBLESHOOT & OPTIMIZE | 25%

USING STATISTICS

SQL INTERNAL JOINS (NESTED SMALL, MERGE LARGE SORTER, HASH LARGE UNSORTED)

TRANSACTIONS (BEGIN, COMMIT, ROLLBACK, XACT_ABORT, TRANCOUNT)Explicit transactions start with the BEGIN TRANSACTION statement and end with the COMMIT or ROLLBACK statement.

XACT_ABORT

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.SET XACT_ABORT ON;GOBEGIN TRANSACTION;...COMMIT TRANSACTION;

XACT_STATE

XACT_STATE returns the following three values 1: The current request has an active user transaction. The request can perform any actions, including

writing data and committing the transaction. 0: There is no active user transaction for the current request. -1: The current request has an active user transaction, but an error has occurred that has

caused the transaction to be classified as an uncommittable transaction. The request cannot commit the transaction or roll back to a savepoint; it can only request a full rollback of the transaction. The request cannot perform any write operations until it rolls back the transaction. The request can only perform read operations until it rolls back the transaction. After the transaction has been rolled back, the request can perform both read and write operations and can begin a new transaction.

So before commit or rollback always 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. If 0, there is no transaction and a commit or rollback operation will generate an error.

@@TRANCOUNT

Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection. Each COMMIT decreases the number by 1 and a Rollback sets it to 0. @@TRANCOUNT cannot be used to determine whether that transaction has been classified as an uncommittable transaction.

https://msdn.microsoft.com/en-us/library/ms188929.aspx

Both the XACT_STATE and @@TRANCOUNT functions can be used to detect whether the current request has an active user transaction. @@TRANCOUNT cannot be used to determine whether that transaction has been classified as an uncommittable transaction. XACT_STATE cannot be used to determine whether there are nested transactions.

ISOLATION LEVELS (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SNAPSHOT, SERIALIZABLE)Read Commited – Default. All readers will only read commited changes

Read Uncommited – reading dirty data

Read Commited Snapshot – eliminates the need for shared locks

Repeatable Read – blocks updates and deletes, but allows new rows. (phantom reads)

Snapshot – similar to repeatable reads but blocks phantom reads

Serializable – Strongest level. All rows are repeatable and new rows are not allowed to be added to the underlying table

TRY/CATCHA TRY…CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection.

BEGIN TRY

-- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH -- Prints error message select error_message()END CATCH;

https://msdn.microsoft.com/en-us/library/ms175976.aspx

ERRORSERROR_STATE()1 means error If error_state()=1 then… @@Error Returns error number @@rowcount Rows affected

RAISE VS THROW THROW is SQL 2012+THROW causes execution to end. You can set the severity level in RAISERAISE can raise system errors. System error numbers are out of range for THROWTHROW allows user defined messageRAISE allows parameters

RAISE

Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically.

RAISERROR (N'This is message %s %d.', -- Message text. 10, -- Severity, 1, -- State, N'number', -- First argument. 5); -- Second argument. -- The message text returned is: This is message number 5.

THROW

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2016.

THROW 51000, 'The record does not exist.', 1;

BEGIN TRY -- Generate divide-by-zero error. SELECT 1/0; END TRY BEGIN CATCH -- Prints error message THROW

END CATCH;

https://msdn.microsoft.com/en-us/library/ms178592.aspx

CURSORS (ROWBASED) VS SET BASED APPROACH

TABLE HINTS (UPDLOCK, ROWLOCK, TABLOCK, …ETC)

QUERY HINTS (OPTION (OPTIMIZED FOR … [UNKNOWN]))

**Where /group/having http://www.midnightdba.com/Jen/2016/10/step-step-group/

**security http://sqlmag.com/database-security/what-every-accidental-dba-needs-know-now-basics-sql-security

REFERENCEShttps://sqlwithmanoj.com/2012/11/16/passed-70-461-exam-querying-microsoft-sql-server-2012/