T sql denali code Day of .Net


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

T sql denali code Day of .Net

  1. 1. USE DENALI_DEMO;GO--Create a SEQUENCEIF EXISTS(SELECT * FROM sys.objects WHERE NAME =mySequence) DROP SEQUENCE mySequenceCREATE SEQUENCE mySequence AS BIGINT --TINYINT, SMALLINT, BIGINT, DECIMAL andNUMERIC (0 scale) START WITH 1 INCREMENT BY 1;--Select values from the sequenceSELECT NEXT VALUE FOR mySequence;SELECT NEXT VALUE FOR mySequence;/*CREATE SEQUENCE [schema_name . ] sequence_name [ <sequence_property_assignment> [ ,…n ] ] [ ; ]<sequence_property_assignment>::={ [ AS { built_in_integer_type | user-defined_integer_type } ] | START WITH <constant> | INCREMENT BY <constant> | { MINVALUE <constant> | NO MINVALUE } | { MAXVALUE <constant> | NO MAXVALUE } | { CYCLE | NO CYCLE } | { CACHE [<constant> ] | NO CACHE }}*/
  2. 2. IF EXISTS(SELECT * FROM sys.objects WHERE name =test1) DROP SEQUENCE test1;CREATE SEQUENCE test1;SELECT NEXT VALUE FOR test1;SELECT NEXT VALUE FOR mySequence;--View Properties of the sequencesSELECT * FROM sys.sequences;--RestartALTER SEQUENCE mySequence RESTART WITH 1;--Use in a query, numbers in order of ProductIDSELECT NEXT VALUE FOR mySequence OVER(ORDER BYProductID) AS SEQ, Name, ProductIDFROM AdventureWorks2008R2.Production.ProductORDER BY ProductID;--Numbers in order of ProductID, but sort results--by NameALTER SEQUENCE mySequence RESTART WITH 1;SELECT NEXT VALUE FOR mySequence OVER(ORDER BYProductID) AS SEQ, Name, ProductIDFROM AdventureWorks2008R2.Production.ProductORDER BY Name;DROP SEQUENCE TEST2CREATE SEQUENCE TEST2
  3. 3. --Multiple tables, columnsTRUNCATE TABLE Table1; -- one int columnTRUNCATE TABLE Table2; -- two int columnsINSERT INTO Table1(Col1,Seq1)VALUES(A,NEXT VALUE FOR mySequence)INSERT INTO Table2(Col1,Seq1,Seq2)VALUES(B,NEXT VALUE FOR mySequence, NEXT VALUE FORmySequence), (C,NEXT VALUE FOR mySequence, NEXT VALUE FORtest1);SELECT Col1, Seq1 FROM Table1;SELECT Col1, Seq1, Seq2 FROM Table2;--CyclingIF EXISTS(SELECT * FROM sys.objects WHERE name =myCount) DROP SEQUENCE myCount;CREATE SEQUENCE myCount AS tinyint START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 5 CYCLE;SELECT NEXT VALUE FOR myCount OVER(ORDER BY ProductID)AS SEQ, Name, ProductIDFROM AdventureWorks2008R2.Production.Product
  4. 4. ORDER BY ProductID;--Use in a transactionTRUNCATE TABLE TestTable;--What is the next number?SELECT name, current_value FROM sys.sequencesWHERE name = mySequence;BEGIN TRANSACTION INSERT INTO TestTable(Col1, Col2) VALUES(a,NEXT VALUE FOR mySequence), (b,NEXT VALUE FOR mySequence), (c,NEXT VALUE FOR mySequence);ROLLBACKSELECT name, current_value FROM sys.sequencesWHERE name = mySequence;--PERMISSIONGRANT INSERT, UPDATE, SELECT ON Table1 TO testuserEXECUTE AS LOGIN = testuserGOINSERT INTO Table1 SELECT f,1000--try to use the sequence objectINSERT INTO Table1 SELECT g,NEXT VALUE FORmySequenceREVERTGRANT UPDATE ON mySequence TO testuser;EXECUTE AS LOGIN = testuser;GO
  5. 5. INSERT INTO Table1 SELECT g,NEXT VALUE FORmySequence;REVERT;DECLARE @range_first_value_output sql_variant, @range_last_value_output sql_variant;EXEC sp_sequence_get_range@sequence_name = NmySequence, @range_size = 30, @range_first_value = @range_first_value_outputOUTPUT, @range_last_value = @range_last_value_output OUTPUT;SELECT @range_first_value_output AS FirstNumber, @range_last_value_output AS LastNumber;--END SEQUENCE--Ad-hoc Query PagingUSE AdventureWorks2008R2;GOSELECT Name, ProductIDFROM Production.ProductORDER BY ProductID;--Get rows 6 and onSELECT Name, ProductIDFROM Production.ProductORDER BY ProductID OFFSET 5 ROWS;
  6. 6. --Start with 6th rows and fetch only 10SELECT Name, ProductIDFROM Production.ProductORDER BY ProductID OFFSET 5 ROWS FETCH NEXT 10 ROWSONLY;--END PAGING--THROWUSE DENALI_DEMOGO--THROWTHROW 500001,an error message,10create table Table_PK(Col1 int primary key)--inside TRY/CATCHBEGIN TRY INSERT INTO Table_PK(COl1) VALUES(1); INSERT INTO Table_PK(COl1) VALUES(1);END TRYBEGIN CATCH INSERT INTOERROR_LOG(ErrorDate,ErrorNumber,ErrorMessage) VALUES(getdate(),ERROR_NUMBER(),ERROR_MESSAGE()); THROW;END CATCH--END THROW
  7. 7. --WITH RESULT SETSEXECUTE (SELECT 1,2)WITH RESULT SETS( (Column1 int NOT NULL) );EXECUTE(SELECT 1)WITH RESULT SETS NONE;EXECUTE(EXECUTE(SELECT 1 AS COL1)WITH RESULT SETS UNDEFINED;)WITH Result sets undefined;EXEC AdventureWorks2008R2.Production.ProductList%Chain%EXEC AdventureWorks2008R2.Production.ProductList%Chain%WITH RESULT SETS ( ([Product Number] int, [Product Name] nvarchar(50), [List Price] money), ([Product Name] nvarchar(50), [Number of Orders] int) );--END WITH RESULT SETS
  8. 8. --SYS.SP_DESCRIBE_FIRST_RESULT_SET--old command returns colum names but not dataUSE AdventureWorks2008R2;GOSET FMTONLY ON;GOSELECT *FROM AdventureWorks2008R2.HumanResources.Employee;SET FMTONLY OFF;EXEC sys.sp_describe_first_result_set NSELECT * FROMAdventureWorks2008R2.HumanResources.Employee;;--Has two result sets, but first is always knownEXEC AdventureWorks2008R2.Production.ProductList%Chain%;EXEC sys.sp_describe_first_result_set NAdventureWorks2008R2.Production.ProductList%Chain%;EXEC sys.sp_describe_first_result_set NIF (1=1) BEGIN EXECAdventureWorks2008R2.Production.ProductList%Chain% END ELSE BEGIN
  9. 9. EXECAdventureWorks2008R2.dbo.uspGetBillOfMaterials 1 END;--END describe first result set--Date/Time functions--Date Time from PartsSELECT DATEFROMPARTS(2011,8,6);SELECT DATETIME2FROMPARTS(2011,8,6,14,30,59,12345,7);--End of monthSELECT EOMONTH(GETDATE());--END Date/Time--Conversion functions--PARSE ( string_value AS data_type [ USING culture ])SELECT PARSE(August 6, 2011 AS SMALLDATETIME);SELECT PARSE(ABCDE AS SMALLDATETIME);--TRY_PARSE ( string_value AS data_type [ USINGculture ] )SELECT TRY_PARSE(August 6, 2011 AS SMALLDATETIME);SELECT TRY_PARSE(ABCDE AS SMALLDATETIME);--TRY_CONVERT ( data_type [ ( length ) ], expression[, style ] )SELECT CONVERT(VARCHAR,GETDATE(),101);SELECT CONVERT(INT,123);SELECT CONVERT(INT, ABC);SELECT TRY_CONVERT(INT, ABC);--END CONVERSION
  10. 10. --Logical Functions--IIF--Current CASESELECT CASE WHEN 1 = 2 THEN 1 equals 2 ELSE 1 doesnot equal 2 END;SELECT IIF(1 = 2, 1 equals 2,1 does not equal 2);Use AdventureWorks2008R2;GOSELECT ProductID, IIF(Color IS NOT NULL,Color, Nocolor recorded) AS ColorFROM Production.Product;--CHOOSESELECT ProductID, CHOOSE(ProductID % 3 +1,Apples,Oranges,Pears)FROM Production.Product;--END Logical functions--String functions--CONCATSELECT ProductID, Color, Size, Color + + SizeFROM Production.ProductWHERE Color IS NOT NULL OR Size IS NOT NULL;SELECT ProductID, Color, Size, CONCAT(Color, ,Size)FROM Production.ProductWHERE Color IS NOT NULL OR Size IS NOT NULL;--FORMATSELECT FORMAT(GETDATE(),MM/dd/yyyy);
  11. 11. SELECT FORMAT(GETDATE(),MMMM dd, yyyy);SELECT FORMAT(1234,C);--END String functions--ENDString functionsCONCAT (Transact-SQL)FORMAT (Transact-SQL)
  12. 12. --OFFSET/*--NEARUSE AdventureWorks2008R2;GOSELECT DocumentNode,TitleFROM Production.DocumentWHERE CONTAINS(Document,Reflector NEAR Assembly);SELECT DocumentNode,TitleFROM Production.DocumentWHERE CONTAINS(Document,NEAR((Reflector,Assembly),5));SELECT DocumentNode, Title, Document, KEY_TBL.RANKFROM Production.Document AS DocTable INNER JOINCONTAINSTABLE(Production.Document, Document,(Reflector NEAR Assembly) ) AS KEY_TBL
  13. 13. ON DocTable.DocumentNode = KEY_TBL.[KEY]ORDER BY KEY_TBL.RANK;--must be in orderSELECT DocumentNode,TitleFROM Production.DocumentWHERE CONTAINS(Document,NEAR((Reflector, Assembly),5,TRUE));--END*//*--Compare to TOP, but TOP doesnt have a skip optionSET STATISTICS IO ON;SELECT TOP(1000) Name, ProductIDFROM Production.ProductORDER BY Name;SELECT Name, ProductIDFROM Production.ProductORDER BY Name OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY;SET STATISTICS IO OFF;*//*--Paging example from BOL, with an enhancement!-- Ensure the database can support the snapshotisolation level set for the query.IF (SELECT snapshot_isolation_state FROM sys.databasesWHERE name = NAdventureWorks2008R2) = 0 ALTER DATABASE AdventureWorks2008R2 SETALLOW_SNAPSHOT_ISOLATION ON;
  14. 14. GO-- Set the transaction isolation level to SNAPSHOTfor this query.SET TRANSACTION ISOLATION LEVEL SNAPSHOT;GO-- Beging the transactionBEGIN TRANSACTION;GO-- Declare and set the variables for the OFFSET andFETCH values.DECLARE @StartingRowNumber int = 1 , @RowCountPerPage int = 3;-- Create the condition to stop the transaction afterall rows have been returned.WHILE (SELECT COUNT(*) FROM HumanResources.Department)>= @StartingRowNumberBEGIN-- Run the query until the stop condition is met.SELECT DepartmentID, Name, GroupName, COUNT(*)OVER()/@RowCountPerPage AS TotalPagesFROM HumanResources.DepartmentORDER BY DepartmentID ASC OFFSET @StartingRowNumber - 1 ROWS FETCH NEXT @RowCountPerPage ROWS ONLY;-- Increment @StartingRowNumber value.SET @StartingRowNumber = @StartingRowNumber +@RowCountPerPage;CONTINUEEND;GO
  15. 15. COMMIT TRANSACTION;GO;SET TRANSACTION ISOLATION LEVEL READ COMMITTED;*//*USE AdventureWorks2008R2;GOSELECT BusinessEntityID, TerritoryID ,DATEPART(yy,ModifiedDate) AS SalesYear ,CONVERT(varchar(20),SalesYTD,1) AS SalesYTD ,CONVERT(varchar(20),AVG(SalesYTD) OVER (PARTITIONBY TerritoryID ORDER BYDATEPART(yy,ModifiedDate) ),1) ASMovingAvg ,CONVERT(varchar(20),SUM(SalesYTD) OVER (PARTITIONBY TerritoryID ORDER BYDATEPART(yy,ModifiedDate) ),1) ASCumulativeTotalFROM Sales.SalesPersonWHERE TerritoryID IS NULL OR TerritoryID < 5ORDER BY TerritoryID,SalesYear;*/