SQL Server - Introduction to TSQL

2,826 views

Published on

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,826
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
99
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Java current version 1.6 Update 171.7 released next year 2010Dynamic languages Parallel computingMaybe closures
  • TEST that I will do:1. Create a new table called Bonus in schema Salary2. Login as Alice and try to access Bonus (with all permissions on Bonus)--> Should not be able to
  • decimalFixed precision and scale numeric data from -10^38 +1 through 10^38 –1. numericFunctionally equivalent to decimal.moneyMonetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit.smallmoneyMonetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit.
  • Date = 3 bytes only DateDate– Enthält nur den Datumswert– Feste Größe von 3 byte– Spanne: 01.01.0001 – 31.12.9999– Bsp: 13-11-2008 oder 2008-11-13Time(n)– Enthält nur den Zeitwert– Variable Größe von 3-5 byte–Genauigkeit bis zu 100 Nanosekunden möglich– Bsp: 08:15:30.11223DateTimeOffset(n)– Enthält Datum und Uhrzeit inklusive der Zeitzonenverschiebung– Variable Größe von 8-10 byte–Genauigkeit bis zu 100 Nanosekunden möglich– Bsp: 2008-11-13 08:15:30.11223 01:00DateTime2(n)– Kombination aus Date und Time Datentyp– Variable Größe von 6-8 byte–Genauigkeit bis zu 100 Nanosekunden möglich– Spanne: 01.01.0001 – 31.12.9999– Bsp: 13-11-2008 08:15:30.11223
  • Needs NTFSTransaction saveNo datasize limitBackup works
  • USE AdventureWorksGO CREATE TABLE DocumentStore(DocIDint PRIMARY KEY, Title varchar(200) NOT NULL,ProductionSpecificationvarchar(20) SPARSE NULL,ProductionLocationsmallintSPARSE NULL,MarketingSurveyGroupvarchar(20) SPARSE NULL ) ;GO
  • Sparse columns require more storage space for nonnull values than the space required for identical data that is not marked SPARSE. The following tables show the space usage for each data type. The NULL Percentage column indicates what percent of the data must be NULL for a net space savings of 40 percent.
  • Clustered Index – Index that configures internal sorting of table(Can be only one on table)
  • Points LinesPolygonsMultipoints
  • http://www.conceptdevelopment.net/Database/Geoquery/
  • http://technet.microsoft.com/en-us/magazine/cc434692(TechNet.10).aspxhttp://msdn.microsoft.com/en-us/library/bb630263.aspxSELECT OrgNode.ToString() AS LogicalNode, * FROM NewOrgORDER BY LogicalNode;GO
  • A Common Table Expression (CTE) is a temporary result set derived from a simple query. A CTE can be used in many of the same ways you use a derived table. CTEs can also contain references to themselves. This allows database developers to write recursive queries. CTEs can also be used in place of views.
  • XML Output – see exampleselect TOP 10 WITH TIES * from AdventureWorks.Person.ContactORDER BY Titleselect ROW_NUMBER() over(order by FirstName), *from AdventureWorksLT.SalesLT.Customerorder by FirstName
  • * The query() method is useful for extracting parts of an XML instance. The XQuery expression evaluates to a list of XML nodes. The subtree rooted at each of these nodes is returned in document order. The result type is untyped XML. * The value() method extracts a scalar value from an XML instance. It returns the value of the node the XQuery expression evaluates to. This value is converted to a Transact-SQL type specified as the second argument of the value() method. * The exist() method is useful for existential checks on an XML instance. It returns 1 if the XQuery expression evaluates to non-null node list; otherwise it returns 0. * The nodes() method yields instances of a special XML data type, each of which has its context set to a different node that the XQuery expression evaluates to. The special XML data type supports the query(), value(), nodes(), and exist() methods, and can be used in count(*) aggregations and NULL checks. All other uses result in an error. * The modify() method permits modifying parts of an XML instance, such as adding or deleting subtrees, or replacing scalar values such as the price of a book from 9.99 to a 39.99.
  • -- Return rows in a random orderSELECT     SomeColumnFROM     SomeTableORDER BY     NEWID()-- repeat 10 timesPRINT 'X'GO 10
  • SQL Server - Introduction to TSQL

    1. 1. SQL Server 2008 for Developers<br />UTS Short Course<br />
    2. 2. Peter Gfader<br />Specializes in <br />C# and .NET (Java not anymore)<br />TestingAutomated tests<br />Agile, ScrumCertified Scrum Trainer<br />Technology aficionado <br />Silverlight<br />ASP.NET<br />Windows Forms<br />
    3. 3. Course Website<br />http://sharepoint.ssw.com.au/Training/UTSSQL/Pages/<br />Course Timetable<br />Course Materials<br />
    4. 4. Course Overview<br />
    5. 5. SQL Management Studio<br />SQL Configuration Manager<br />Consoles<br />SQLCMD<br />PowerShell<br />SQL Profiler<br />SQL Database Tuning Advisor<br />Last Week<br />
    6. 6. How to setup maintenance plans over night<br />Database encryption<br />Data<br />Source code (Stored procs)<br />Best practices<br />Typical maintenance plans<br />Policies<br />Last Week - Additional<br />
    7. 7. Modify maintenance plan<br />2nd page in wizard (new plan)<br />
    8. 8. Encrypting data - Transparent Data Encryption (TDE)<br />http://msdn.microsoft.com/en-us/library/bb934049.aspx<br />http://www.acorns.com.au/blog/?p=147<br />Encrypting Connections to SQL Server<br />http://msdn.microsoft.com/en-us/library/ms189067.aspx<br />Encrypting source code<br />http://www.codeproject.com/KB/database/ProtectSQLCodeObject.aspx<br />Database encryption<br />
    9. 9. http://ola.hallengren.com/<br />Steps<br />Backup<br />Integrity check <br />Index optimization<br />Solution used in<br />mission-critical environments in <br />many organizations.<br />Best practices - Maintenance<br />
    10. 10. Security Best Practices <br />http://download.microsoft.com/download/8/5/e/85eea4fa-b3bb-4426-97d0-7f7151b2011c/SQL2005SecBestPract.doc<br />Security Best Practices Checklist<br />http://technet.microsoft.com/en-us/library/cc966456.aspx<br /> <br />Best practices - Security<br />
    11. 11. Create a schema called Salary<br />Create a table called Employees in Schema<br />Create a user called Manager<br />Give only manager permission to update/insert/delete in schema<br />Create a user called Peter<br />Give Peter only read to schema (=salary)<br />Create a user Alice<br />Deny everything for Alice in Salary<br />Homework?<br />
    12. 12. Agenda<br />New Data Types<br />Inline variable assignment<br />Table Value Parameters<br />DDL Triggers<br />CTE (Common Table Expressions)<br />TOP %, XML Queries<br />PIVOT/UNPIVOT<br />ADO.NET<br />
    13. 13. Datatypes - Exact Numerics<br />bigint, int, smallint, tinyint<br />-2^63 ... 2^63-1<br />0..255<br />Bit (0 or 1)<br />decimal = numeric<br />Exact type<br />Numbers -10^38 +1 ... 10^38 –<br />Money, smallmoney<br />accuracy to a ten-thousandth money unit<br />Smallmoney = smaller money<br />
    14. 14. Datatypes – Approximate Numerics<br />Floating point numeric data<br />float<br />real<br />
    15. 15. Datatypes - text<br />char<br />Fixed length<br />varchar<br />Variable length<br />
    16. 16. Datatypes - text<br />char, varchar, text<br />Ascii - 1 byte<br />nchar, nvarchar, ntext<br />Unicode - 2 bytes<br />binary, varbinary, image<br />
    17. 17. Date and Time<br />SQL 2008 now has the following data types to represent time:<br />DateTime<br />SmallDateTime<br />Date<br />Time<br />DateTime2 – really a BigDateTime<br />Min Date is 1st Jan 0000<br />Max date 31st Dec 9999 – Y10K BUG!!<br />DateTimeOffset<br />
    18. 18. Date Time details<br />
    19. 19. Datatypes - Other<br />cursor<br />table<br />Timestamp = rowversion<br />binary number <br />Reflects data modifications<br />uniqueidentifier = Guid<br />Format: 04c4ce04-16c1-406f-a895-5dd321db7f0b<br />
    20. 20. New Data Types<br />Filestream<br />Sparse Columns<br />Filtered Indexes<br />Spatial Data<br />HierarchyID<br />DATE and TIME data types<br />
    21. 21. Example: Storing images<br />I am designing an Employee table that needs to cater for employee photographs. What should I do?<br />
    22. 22. blob vs. file system<br />I am designing an Employee table that needs to cater for employee photographs. What should I do?<br />You can store the image in the database (blob)<br />You can store a URL to the image in the database (Recommended for SQL2005)<br />http://www.ssw.com.au/ssw/standards/Rules/RulestoBetterSQLServerdatabases.aspx#ImageReplaceWithURL<br />
    23. 23. blob<br /><ul><li>You can store the image in the database (blob)</li></ul>Database grows really big<br />Backups take longer<br />Your code needs to convert the bytes back into an image<br />Your images are in sync with your data<br />
    24. 24. File system<br /><ul><li>You can store a URL to the image in the database (Recommended for SQL2005)</li></ul>Database is smaller<br />Easily validate or change the image (you can look at it on the file system)<br />Data could become out of sync with the file system<br />Need to backup the database and the file system<br />
    25. 25. Filestream<br />Filestream to the rescue<br />Implemented as a special varbinary(max) where data is stored as a blob on the file system<br />Allows you to have transactionally consistent<br />Integrated backup and restore of your binary images<br />Size limitation is the size of your hard drive’s free space<br />
    26. 26. Problem<br />Q: I’ve got an Contacts table with 200,000 rows. To support the latest Web 2.0 trends we want to also record the contact’s blog address. What should I do?<br />
    27. 27. Solution?<br />A: Just add a new BlogUrl column in<br />
    28. 28. Solution?<br />A: Just add a new BlogUrl column in<br />Q: What’s the problem with that?<br />A: Most of the entries in your table will be null, it wastes a lot of database space<br />
    29. 29. Solution<br />Use a sparse column<br />These columns are new to SQL 2008<br />They are optimized for storing NULL values<br />
    30. 30. Sparse Columns<br />
    31. 31. Sparse Columns<br />
    32. 32. Sparse Columns<br />
    33. 33. Filtered Indexes<br />Allows you to add an index to a column with a where clause<br />Useful for indexing columns with null values in them<br />
    34. 34. Spatial Data Types<br />Geometry<br />Geography<br />Virtual Earth Integration<br />Planar vs Geodetic Algorithms<br />Separate install for spatial assemblies<br />http://www.conceptdevelopment.net/Database/Geoquery/<br />
    35. 35. Spatial Datatypes Hierarchy<br />
    36. 36. Spatial Data Types<br />Geometry allows you to represent and process polygons<br />
    37. 37. How do I represent an Org Chart?<br />Employee with a ManagerID column (self join)<br />New HierarchyID data type<br />Can be indexed using:<br />Depth First <br />Breadth First<br />
    38. 38. Depth First Search<br />A depth-first index, rows in a subtree are stored near each other. For example, all employees that report through a manager are stored near their managers' record.<br />
    39. 39. Breadth First Search<br />A breadth-first stores the rows each level of the hierarchy together. For example, the records of employees who directly report to the same manager are stored near each other.<br />
    40. 40. Inline Variable Assignment<br />Instead of:<br />DECLARE @myVar intSET @myVar = 5<br />You can:<br />DECLARE @myVar int = 5<br />
    41. 41. Table Value Parameters<br />Pass in a table as an argument to a SPROC<br />Instead of:<br />exec sp_MySproc 'murphy,35;galen,31;samuels,27;colton,42‘ <br />SPROC needs to then parse that string<br />
    42. 42. Table Value Parameters<br />You can do this instead<br />CREATE TYPE PeepsType AS TABLE (Name varchar(20), Age int) DECLARE @myPeeps PeepsType INSERT @myPeeps SELECT 'murphy', 35 INSERT @myPeeps SELECT 'galen', 31 INSERT @myPeeps SELECT 'samuels', 27 INSERT @myPeeps SELECT 'colton', 42exec sp_MySproc2 @myPeeps <br />
    43. 43. Table Value Parameters<br />The SPROC would look like this:<br />CREATE PROCEDURE sp_MySproc2(@myPeeps PeepsType READONLY)<br />
    44. 44. DDL Triggers<br />Auditing, regulating schema changes, capture events on create_table, alter_procedure, drop_login etc<br />
    45. 45. PIVOT<br />
    46. 46. CTE (Common Table Expression) Before<br />
    47. 47. CTE (Common Table Expressions) After<br />
    48. 48. More features<br />ROW NUMBER – see example<br />TRY/Catch in queries – see example<br />Top % WITH TIES<br />select top with tie feature( if top 10 and there are 15 that match number 10 will bring back all 15)<br />
    49. 49. Working with XML - RAW<br />SELECT TOP 3 Person.FirstName, Person.LastName, PersonPhone.PhoneNumber<br />FROM AdventureWorks.Person.Person<br /> INNER JOIN AdventureWorks.Person.PersonPhone ON<br />PersonPhone.BusinessEntityID = Person.BusinessEntityID<br />FOR XML RAW <br />
    50. 50. Working with XML - RAW<br /><row FirstName="Ken" LastName="Sánchez" PhoneNumber="697-555-0142"/><br /><row FirstName="Terri" LastName="Duffy" PhoneNumber="819-555-0175"/><br /><row FirstName="Roberto" LastName="Tamburello" PhoneNumber="212-555-0187"/><br />
    51. 51. Working with XML - RAW<br />What happened to our relationships?<br />RAW doesn’t show our table relationships but gives us a flat XML hierarchy<br />
    52. 52. Working with XML - Auto<br />SELECT TOP 3 Person.FirstName, Person.LastName, PersonPhone.PhoneNumber<br />FROM AdventureWorks.Person.Person<br /> INNER JOIN AdventureWorks.Person.PersonPhone ON<br />PersonPhone.BusinessEntityID = Person.BusinessEntityID<br />FOR XML AUTO<br />
    53. 53. Working with XML - Auto<br /><AdventureWorks.Person.PersonFirstName="Ken" LastName="Sánchez"><br /><AdventureWorks.Person.PersonPhonePhoneNumber="697-555-0142"/><br /></AdventureWorks.Person.Person><br />
    54. 54. Working with XML - Auto<br />Great, but what if I needed to format the XML to output into a certain schema<br />
    55. 55. Working with XML - Explicit<br />SELECT TOP 3 <br /> 1 AS TAG,<br /> NULL AS PARENT,<br />BusinessEntityID AS [Person!1!BusinessEntityID],<br />FirstName AS [Person!1!FirstName!ELEMENT]<br />FROM AdventureWorks.Person.Person<br />FOR XML EXPLICIT<br />
    56. 56. Working with XML - Explicit<br /><Person BusinessEntityID="285“><br /><FirstName>Syed</FirstName><br /></Person><br /><Person BusinessEntityID="293"><br /><FirstName>Catherine</FirstName><br /></Person><br /><Person BusinessEntityID="295"><br /><FirstName>Kim</FirstName><br /></Person><br />
    57. 57. Working with XML - Explicit<br />Can control how the XML gets output<br />Ugly query<br />Is there a better way?<br />
    58. 58. Working with XML - PATH<br />SELECT TOP 3<br />BusinessEntityID "Person/@BusinessEntityID",<br />FirstName "Person/FirstName"<br />FROM AdventureWorks.Person.Person<br />FOR XML PATH ('') <br />
    59. 59. Working with XML - XQuery<br />XQuery is a query language for XML Data<br />
    60. 60. XQuery – Declaring our XML string<br />DECLARE @x XML<br />SET @x = '<christmaslist><person name = "betty" gift = "camera"/><person name = "zach" gift = "elmo doll"/><person name = "brad" gift = "socks"/></christmaslist>'<br />
    61. 61. XQuery - Querying<br />SELECT @x.exist('/christmaslist/person[@gift="socks"]')<br />SELECT @x.exist('/christmaslist/person[@gift="lump of coal"]')<br />SELECT @x.exist('/christmaslist/person[@gift="Socks"]‘)<br />SELECT @x.value('/christmaslist[1]/person[1]/@name', 'VARCHAR(20)‘)<br />SELECT @x.query('/christmaslist/person')<br />
    62. 62. XQuery - Querying<br />query()<br />value()<br />exist()<br />nodes()<br />modify()<br />
    63. 63. XQuery - Resources<br />http://msdn.microsoft.com/en-us/library/ms345117.aspx<br />
    64. 64. ADO.NET<br />ADO.NET gives you full control over how you access and retrieve data from the data source<br />Strongly typed data sets<br />Work in disconnected mode<br />
    65. 65. ADO.NET<br />SQLConnection<br />Manages the connection to the database<br />SQLCommand<br />Defines the data to be read, updated etc.<br />SQLDataAdapter<br />Runs the SQLCommand against the database<br />DataSet<br />A complete in-memory copy of the data (tables, relationships, data types…)<br />Search, filter, navigate your data – without even being connected to the database!<br />
    66. 66. TSQL Tricks<br />Randomize Select output<br />Repeat statements with GO x<br />
    67. 67. Resources 1/2<br />Spatial Data playground<br />http://www.conceptdevelopment.net/Database/Geoquery/<br />Hidden Features in SQL Server<br />http://stackoverflow.com/questions/121243/hidden-features-of-sql-server<br />Top 10 Hidden Gems in SQL Server<br />http://technet.microsoft.com/en-au/library/cc917696.aspx<br />
    68. 68. What to do when you take over a new SQL Server box?<br />http://www.brentozar.com/sql/blitz-minute-sql-server-takeovers/<br />Resources 2/2<br />
    69. 69. Session 2 Lab <br />T-SQL Enhancements<br />Download from Course Materials Site (to copy/paste scripts) or type manually<br />http://sharepoint.ssw.com.au/training/UTSSQL/<br />
    70. 70. Where Else Can I Get Help?<br />Where else can I get help?<br />Free chats and webcasts<br />List of newsgroups<br />Microsoft community sites<br />Community events and columns<br />www.microsoft.com/technet/community<br />
    71. 71. 3things…<br />PeterGfader@ssw.com.au<br />http://peitor.blogspot.com<br />twitter.com/peitor<br />
    72. 72. Thank You!<br />Gateway Court Suite 10 81 - 91 Military Road Neutral Bay, Sydney NSW 2089 AUSTRALIA <br />ABN: 21 069 371 900 <br />Phone: + 61 2 9953 3000 Fax: + 61 2 9953 3105 <br />info@ssw.com.auwww.ssw.com.au <br />

    ×