Monday, January 30, 2012

SQL Server 2012 (Denali): OFFSET and FETCH Limitations

OFFSET and FETCH can be used in any query that allows TOP and ORDER BY with the following limitations:
  1. The OVER clause does not support OFFSET and FETCH.
  2. OFFSET and FETCH cannot be specified directly in INSERT, UPDATE, MERGE, and DELETE statements, but can be specified in a subquery defined in these statements. For example, in the INSERT INTO SELECT statement, OFFSET and FETCH can be specified in the SELECT statement.
  3. In a query that uses UNION, EXCEPT or INTERSECT operators, OFFSET and FETCH can only be specified in the final query that specifies the order of the query results.
  4. TOP cannot be combined with OFFSET and FETCH in the same query expression (in the same query scope).

SQL Server 2012 (Denali) New Features: Limit number of rows using OFFSET and FETCH clause

Limiting the number of rows returned

The following example specifies an integer constant as the value for the OFFSET and FETCH clauses. The first query returns all rows sorted by the column ID. Compare the results returned by this query with the results of the two queries that follow it. The next query uses the clause OFFSET 5 ROWS to skip the first 5 rows and return all remaining rows. The final query uses the clause OFFSET 0 ROWS to start with the first row and then uses FETCH NEXT 10 ROWS ONLY to limit the rows returned to 10 rows from the sorted result set.

-- Return all rows sorted by the column DepartmentID.
SELECT ID, Name, GroupName
FROM Department

-- Skip the first 5 rows from the sorted result set and return all remaining rows.
SELECT ID, Name, GroupName
FROM Department

-- Skip 0 rows and return only the first 10 rows from the sorted result set.
SELECT ID, Name, GroupName
FROM Department

SQL Server 2012 (Denali) New Features for Developers (Programming Enhancements)

Programmability enhancements in the Database Engine include FileTables, statistical semantic search, property-scoped full-text search and customizable proximity search, ad-hoc query paging, circular arc segment support for spatial types, support for sequence objects, default support for 15,000 partitions, and numerous improvements and additions to Transact-SQL.

Native XML Web Services (SOAP/HTTP endpoints) is Removed:
Beginning in Microsoft SQL Server 2012 Release Candidate 0 (RC 0), you can no longer use CREATE ENDPOINT or ALTER ENDPOINT to add or modify SOAP/HTTP endpoints.

The FileTable feature builds on top of the SQL Server FILESTREAM technology to bring support for the Windows file namespace and compatibility with Windows applications to the file data stored in SQL Server. This lets an application integrate its storage and data management components, and provides integrated SQL Server services (including full-text search and semantic search) over unstructured data and metadata, along with easy policy management and administration.

In summary, you can now store files and documents in special tables in SQL Server, but access them from Windows applications as if they were stored in the file system, without making any changes to the Windows applications.

Metadata Discovery:
The SET FMTONLY option for determining the format of a response without actually running the query is replaced with
sys.dm_exec_describe_first_result_set, and

EXECUTE Statement
The EXECUTE statement can now specify the metadata returned from the statement by using the WITH RESULT SETS argument.

A new family of supplementary characters (SC) collations can be used with the data types nchar, nvarchar and sql_variant.
For example: Latin1_General_100_CI_AS_SC or, if using a Japanese collation, Japanese_Bushu_Kakusu_100_CI_AS_SC.
These collations encode Unicode characters in the UTF-16 format. Characters with codepoint values larger than 0xFFFF require two consecutive 16-bit words. These characters are called supplementary characters, and the two consecutive 16-bit words are called surrogate pairs. SC collations can improve searching and sorting by functions that use the Unicode types nchar and nvarchar. For more information, see Collation and Unicode Support.
UTF-16 Supplementary Characters (SC) Collation Option for XML

Ad-hoc Query Paging Implementation
You can specify a range of rows returned by a SELECT statement based on row offset and row count values that you provide. This is useful when you want to control the number of rows sent to a client application for a given query.
FROM Person

New Spatial Features
Circular Arc Segment Support for Spatial Types

Three new sub-data types for geometry and geography data types can be used to store circular arc segments, CircularString, CompoundCurve, and CurvePolygon. Methods for geography and geometry data types support the new circular arc segment data types. There are new methods for geometry and geography data types that work with circular arc segments, OGC Methods on Geography Instances, OGC Methods on Geometry Instances, Extended Methods on Geography Instances, Extended Methods on Geometry Instances and SQL MM Methods on Geography Instances. There are new static aggregate methods for geometry data type and geography data type, Extended Static Geography Methods and Extended Static Geometry Methods.

Sequence ObjectsA sequence object is a user-defined schema-bound object that generates a sequence of numeric values according to the specification with which the sequence was created. It operates similar to an identity column, but sequence numbers are not restricted to use in a single table.

THROW statementThe THROW statement can be used to raise an exception and transfer execution to a CATCH block of a TRY…CATCH construct.

14 New Functions and 1 Changed Function:

Microsoft SQL Server 2012 Release Candidate 0 (RC 0) introduces 14 new built-in functions. These functions ease the path of migration for information workers by emulating functionality that is found in the expression languages of many desktop applications. However these functions will also be useful to experienced users of SQL Server.

The new functions are:
Conversion functions    PARSE
Date and time functions    DATEFROMPARTS
Logical functions
String functions

In addition to the 14 new functions, one existing function has been changed. The existing LOG function now has an optional second base parameter.

SQL Server Express LocalDBSQL Server Express LocalDB is a new lightweight edition of Express that has all its programmability features, yet runs in user mode and has a fast, zero-configuration installation and short list of pre-requisites. The LocalDB edition of SQL Server is targeted to program developers. LocalDB installation copies a minimal set of files necessary to start the SQL Server Database Engine. To use the SQL Server Database Engine, developers connect directly to the database files and the SQL Server infrastructure is transparent to them. Developer Tools can provide developers with a SQL Server Database Engine that lets them write and test Transact-SQL code without having to manage a full server instance of SQL Server. An instance of SQL Server Express LocalDB is managed by using the SqlLocalDB.exe utility. SQL Server Express LocalDB should be used in place of the SQL Server Express user instance feature which is deprecated.

New and Enhanced Query Optimizer HintsThe syntax for the FORCESEEK table hint has been modified.
You can now specify an index and index columns to further control the access method on the index. The existing FORCESEEK syntax remains unmodified and works as before. No changes to applications are necessary if you do not plan to use the new functionality.

The FORCESCAN table hint has been added. It complements the FORCESEEK hint by specifying that the query optimizer use only an index scan operation as the access path to the table or view referenced in the query. The FORCESCAN hint can be useful for queries in which the optimizer underestimates the number of affected rows and chooses a seek operation rather than a scan operation. FORCESCAN can be specified with or without an INDEX hint.

Extended Event EnhancementsThe following new Extended Events are available.
    Fields: worker_address, number_pages, page_size, page_location, allocator_type, page_allocator_type, pool_id
    Fields: worker_address, number_pages, page_size, page_location, allocator_type, page_allocator_type, pool_id
    Fields: worker_address, failure_type, allocation_failure_type, resource_size, pool_id, factor

The following Extended Events have been modified.
    Fields removed: single_pages_kb, multiple_pages_kb
    Fields added: target_kb, pages_kb

    Fields removed: single_pages_kb, multiple_pages_kb
    Fields added: target_kb, pages_kb

OVER Clause Support Enhanced
The OVER clause has been extended to support window functions. Window functions perform a calculation across a set of rows that are in some relationship to the current row. For example, you can use the ROWS or RANGE clause over a set of rows to calculate a moving average or cumulative total.
In addition, ordering rows within a partition is now supported in the aggregate functions that allow the OVER clause to be specified.

Analytic Functions
The following analytic functions have been added.

SQL Server 2012 (Denali) New Features for Developers (Programming Enhancements) - Sequences

Sequence is a user defined object that generates a sequence of a number. Here is an example using Sequence. It operates similar to an identity column, but sequence numbers are not restricted to use in a single table.

How to create Sequence:
/****** Create Sequence Object ******/

/****** Create Temp Table ******/
FullName nvarchar(100) NOT NULL
How to get Next Value For Sequence:
/****** Insert Some Data ******/
INSERT @Person (ID, FullName)
SequenceObj, 'Brian Lauber'),
(NEXT VALUE FOR MySequence, 'Joel Winstead'),
(NEXT VALUE FOR MySequence, 'Patrick Murphy');

/****** Show the Data ******/
SELECT * FROM @Person;

The results would look like this:
ID FullName
Brian Lauber
2 Joel Winstead
3 Patrick Murphy
Viewing Details About Sequences on Your SQL Server
You can query SQL Server to show the sequences that are in a database.
SELECT * FROM sys.sequences 

When to use Sequence vs Identity Columns

Use sequences instead of identity columns in the following scenarios:
  1. The application requires a number before the insert into the table is made.
  2. The application requires sharing a single series of numbers between multiple tables or multiple columns within a table.
  3. The application must restart the number series when a specified number is reached. For example, after assigning values 1 through 10, the application starts assigning values 1 through 10 again.
  4. The application requires sequence values to be sorted by another field. The NEXT VALUE FOR function can apply the OVER clause to the function call. The OVER clause guarantees that the values returned are generated in the order of the OVER clause's ORDER BY clause.
  5. An application requires multiple numbers to be assigned at the same time. For example, an application needs to reserve five sequential numbers. Requesting identity values could result in gaps in the series if other processes were simultaneously issued numbers. Calling sp_sequence_get_range can retrieve several numbers in the sequence at once.
  6. You need to change the specification of the sequence, such as the increment value.
Sequence Limitations:
Unlike identity columns, whose values cannot be changed, sequence values are not automatically protected after insertion into the table. To prevent sequence values from being changed, use an update trigger on the table to roll back changes.

Uniqueness is not automatically enforced for sequence values. The ability to reuse sequence values is by design. If sequence values in a table are required to be unique, create a unique index on the column. If sequence values in a table are required to be unique throughout a group of tables, create triggers to prevent duplicates caused by update statements or sequence number cycling.

The sequence object generates numbers according to its definition, but the sequence object does not control how the numbers are used. Sequence numbers inserted into a table can have gaps when a transaction is rolled back, when a sequence object is shared by multiple tables, or when sequence numbers are allocated without using them in tables. When created with the CACHE option, an unexpected shutdown, such as a power failure, can lose the sequence numbers in the cache.

More on Sequences: