SQL Server 2008 for .NET Developers
Lynn Langit – Developer Evangelist – Microsofthttp://blogs.msdn.com/SoCalDevGal
What Will We cover?• SQL Server Spatial support• BLOB storage (Filestream)• T-SQL Enhancements
• Table-valued parameters• New date / time • More
• Visual Studio integration• SQL CLR• Business Intelligence
• Reporting Services• More
What is Spatial Data?Location-based questions
• Which roads intersect property or each other?• How many stores/restaurants/houses/car dealerships are
located within a geographical area?Spatial Data Types
• Geometry• Flat Earth model & X, Y coordinates
• Geography• Round Earth model uses Latitude and Longitude
coordinates• Can span only one logical hemisphere (more will throw
exception)Query for location info as any SQL Server data type
• Data types dictated by OpenGIS standard• New spatial index type
Representing Spatial DataGeospatial data in SQL Server
• Stored in proprietary binary format• Can be input using simple text
• Parse methods convert text into internal storage format• Represents areas using
• Points, Linestrings, Polygons• MultiPoints, MultiLinestrings, MultiPolygons• GeomCollections
Define Polygons in counter-clockwise direction• Interior areas (“holes”) must be defined in clockwise
directionSupports various calculations and methods
• Spatial Reference ID (SRID) identifies ellipsoid (flat/round, meters/feet)
• Only instances with like SRID can be directly compared
Demo
SQL Server Geospatial and Virtual Earth
About BLOBs1. Old way #1
• Store BLOBs in DB as varbinary (max) up to 2 GB each• Easier management, but can be poor performance
2. Old way # 2• Store BLOBS in File system, path (link) in db• Good performance, but complex management
3. New way• Best of both via Filestream attribute• Applied to varbinary(max) data type• Integrated database security• Uses dedicated Filegroup (easier maintenance)• Limits *no snapshots or mirroring and more
Using Filestream1. Enable Filestream for the machine
• For T-SQL access• For file I/O streaming access• Name of share for storage• For streaming remote clients• Required integrated security
2. Enable Filestream for the server instance• sp_configure filestream_access_level, (0, 1, 2)• Can limit to T-SQL access only (option 1)
3. Create Filestream-enabled database• FILEGROUP FgName CONTAINS FILESTREAM (NAME = …)• Name is the directory (storage) name• Name (i.e. folder) must NOT exist prior to creating DB
4. Create table with Filestream column(s)• With specific requirements, next slide>>
Filestream Columns1. Tables with Filestream columns must…
• Contain a Uniqueidentifier column that is• Not nullable• Uses the ROWGUIDCOL attribute• Max one per table• Has a unique constraint on it
2. Can have more than ‘Filestream’ column• Varbinary(max) with Filestream attribute• Will probably have a default value assigned
3. Can be manipulated using • T-SQL• OpenSqlFilestream function - sample• Performance comparison here
Demo
Using Filestream
Enhancements to T-SQL• Table Value Parameters• New Date/Time types• Time zone awareness• New MERGE keyword• New shorthand notation
Table Value ParametersCREATE TYPE as TABLE• Multiple tables inserted/updated within single
transaction (MARS-like capability for writing)• Can pass strongly-typed arrays to stored proc
as single callADO.NET updated to include support• Param type: SqlDbType.Structured• Can use PK, Unique, Check constraints• Index only for PK or Unique, no stats • Can specify the sort order• Can NOT use Defaults
When to use TVPs• TVPs• Pass large number of rows – uses
tempdb• Results in simpler CRUD stored procs• READONLY after initial population
• Temp table or CTE • CTEs – no indexing, in memory (unless
out of memory, then in tempdb)• Can not pass as param
Demo
T-SQL EnhancementsTable Valued Parameters
Dates and TimeSeveral new types added• datetime2• date• time• datetimeoffset
New functions added• CONVERT• SYS* Functions• DATEDIFF
MERGEInsert, Update, Delete with one keyword• Merge two tables, source and target• WHEN MATCHED• WHEN TARGET NOT MATCHED• WHEN SOURCE NOT MATCHED
• Syntax and use can be complex• MERGE syntax from SQL Server BOL
Shorthand NotationLike .NET languages (C# or Visual
Basic .NET)• Declare variable & assign value in one
line of code• Compound assignment, i.e ‘+=‘, etc..
Demo
T-SQL EnhancementsDate/Time, Merge, Shorthand
Visual Studio Integration
Enhanced project types• Analysis Services• Integration Services• Reporting Services
Entity FrameworkCLR Integration
Entity FrameworkModels relational data using entities (OR/M
tool)• Can model any relational data source for data access
(provider may be required)• Application-specific domain• You can work at a higher level of abstraction• Appropriate amount of information returned• Lazy-loaded
What is an entity?• Structurally like an object (noun)
• Has scalars and relationships• Has identity• Not tied specifically to SQL Server
Demo
Visual Studio IntegrationEntity Framework
SQL CLRSQL CLR is “off by default” for security reasons
• Must activate (instance) then per database to enable• Code executes in SQL Server processing stream
SQL Server has the ability to execute managed code• Stored procedures & Triggers• User-defined Types & Aggregates – extended size (up
to 2 GB)• Regular Functions & Table value functions
Use mostly for complex processing• Use for Functions or Aggregates• Do not use for CRUD operations
Programming SQL CLR
Use Visual Studio templates for SQL CLR constructs• Uses Database project type• Can be remotely debugged • Metadata (attributes) control SQL Server behavior
• Microsoft.SqlServer.Server.xxx• SqlProcedure, SqlFunction, SqlUserDefinedAggregate, SqlTrigger, SqlUserDefinedType, SqlFacet, SqlMethod
Microsoft.SqlServer.Server namespace (retrieves/returns data)• Very ADO.NET-like, but not ADO.NET• Uses SqlContext.Pipe• Assign CAS permission set (Safe, External, Unsafe)• Use for complex processing, i.e. RegEx parsing, etc…
Demo
Visual Studio IntegrationSQL CLR
Business IntelligenceSSAS – Analysis Services
• Date storage and query• OLAP cubes or Data Mining Structures• BIDS to create• SSMS to administer
SSIS – Integration Services• ETL tool
SSRS - Reporting Services• Enterprise Reporting
BI can use any data sourceData WarehousingData Mining
Reporting ServicesSQL Server standard for reporting
• Managed enterprise reporting• Ad-hoc reporting• Embedded reporting• Web-based reporting• Included in SQL Server 2008 Express w/Advanced Services
Reports can be formatted in a variety of ways• PDF, Word 2007, HTML
Reports are exposed via a Web Service• Can be integrated with SharePoint• Dependency on IIS removed (uses http.sys)
Programming ReportsDesign reports in Visual Studio 2008 SP1
• Query for data• Assign query results to report• Design report style
• Colors, Fonts, etc…• Deploy report
• Web Service• SharePoint Services
Wizard available for initial report design – also Report BuilderEnhanced configuration and administration tool
Demo
Visual Studio IntegrationReporting Services and more
But there’s more…• For Developers
• Change Data Capture• Filtered Indexes• Hierarchy ID ( )• Sparse data columns• XML Enhancements• Integrated Full-Text Search
• For Administrators• Policy-based management• Auditing enhancements• Transparent Encryption• Compression• PowerShell integration• More…
Lynn’s bloghttp://blogs.msdn.com/SoCalDevGal
Microsoft Press Publications
Get Microsoft Software for FREE
For high school and college students - DreamSparkFor startup businesses - BizSparkFor everyone - Express editions – VS and SQL - here