Tuesday, 22 September 2015

Types of Join in SQL Server

Introduction

In this tip, I am going to explain about types of join.

What is join??

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.
There are many types of join.
  • Inner Join
    1. Equi-join
    2. Natural Join
  • Outer Join
    1. Left outer Join
    2. Right outer join
    3. Full outer join
  • Cross Join
  • Self Join

Using the Code

Join is very useful to fetching records from multiple tables with reference to common column between them.
To understand join with example, we have to create two tables in SQL Server database.
  1. Employee
    create table Employee(
     
    id int identity(1,1) primary key,
    Username varchar(50),
    FirstName varchar(50),
    LastName varchar(50),
    DepartID int
     
    ) 
  2. Departments
  3. create table Departments(
     
    id int identity(1,1) primary key,
    DepartmentName varchar(50)
     
    ) 
Now fill Employee table with demo records like that.

Fill Department table also like this....

1) Inner Join

The join that displays only the rows that have a match in both the joined tables is known as inner join.
select e1.Username,e1.FirstName,e1.LastName,e2.DepartmentName _
from Employee e1 inner join Departments e2 on e1.DepartID=e2.id
It gives matched rows from both tables with reference to DepartID of first table and id of second table like this.

Equi-Join
Equi join is a special type of join in which we use only equality operator. Hence, when you make a query for join using equality operator, then that join query comes under Equi join.
Equi join has only (=) operator in join condition.
Equi join can be inner join, left outer join, right outer join.
Check the query for equi-join:
SELECT * FROM Employee e1 JOIN Departments e2 ON e1.DepartID = e2.id

2) Outer Join

Outer join returns all the rows of both tables whether it has matched or not.
We have three types of outer join:
  1. Left outer join
  2. Right outer join
  3. Full outer join
a) Left Outer join
Left join displays all the rows from first table and matched rows from second table like that..
 SELECT * FROM Employee e1 LEFT OUTER JOIN Departments e2
ON e1.DepartID = e2.id 
Result:

b) Right outer join
Right outer join displays all the rows of second table and matched rows from first table like that.

 SELECT * FROM Employee e1 RIGHT OUTER JOIN Departments e2
ON e1.DepartID = e2.id
Result:

3) Full outer join
Full outer join returns all the rows from both tables whether it has been matched or not.
 SELECT * FROM Employee e1 FULL OUTER JOIN Departments e2
ON e1.DepartID = e2.id 
Result:

3) Cross Join

A cross join that produces Cartesian product of the tables that are involved in the join. The size of a Cartesian product is the number of the rows in the first table multiplied by the number of rows in the second table like this.
SELECT * FROM Employee cross join Departments e2
You can write a query like this also:
SELECT * FROM Employee , Departments e2

 4) Self Join

Joining the table itself called self join. Self join is used to retrieve the records having some relation or similarity with other records in the same table. Here, we need to use aliases for the same table to set a self join between single table and retrieve records satisfying the condition in where clause.
SELECT e1.Username,e1.FirstName,e1.LastName from Employee e1 _
inner join Employee e2 on e1.id=e2.DepartID
Here, I have retrieved data in which id and DepartID of employee table has been matched:

Points of Interest

Here, I have taken one example of self join in this scenario where manager name can be retrieved by managerid with reference of employee id from one table.
Here, I have created one table employees like that:

If I have to retrieve manager name from manager id, then it can be possible by Self join:
select e1.empName as ManagerName,e2.empName as EmpName _
from employees e1 inner join employees e2 on e1.id=e2.managerid
Result:

Sunday, 20 September 2015

SQL Server 2012: Top New Features for .NET Developers

Like its predecessors SQL Server 2008 and SQL Server 2008 R2, SQL Server 2012 boasts many features and improvements targeted at business intelligence (BI) and operations personnel (i.e., DBAs). But that doesn't mean that SQL Server 2012 ignores developers. In fact, SQL Server 2012 includes a number of great improvements and features in the form of new tooling, coding and programmability enhancements, and even new improvements to the underlying SQL Server engine that developers can take advantage of. Let's run down the list of new features that will benefit .NET developers who use SQL Server. For more information, see "Free SQL Server Resources for Developers" and "SQL Server 2012 Brings DBAs and Developers Together."

New SQL Server 2012 Tooling


SQL Server 2012 boasts some exceptional tooling improvements in the form of a significant upgrade to SQL Server Management Studio (SSMS) and a replacement of Business Intelligence Development Studio (BIDS), resulting in developer-related additions to Visual Studio 2010 and the release of SQL Server Data Tools (SSDT). At the heart of all of these tooling changes, however, is the fact that SQL Server 2012 has been "upgraded" such that SSMS and all associated developer tooling now runs atop the Visual Studio 2010 engine. SQL Server Management Studio 2012. SSMS 2012 packs a number of powerful productivity benefits that developers who use SSMS for development tasks will end up loving. The most obvious change to SSMS is that it's built on Visual Studio 2010, meaning that it picks up a new, darker theme that more closely matches the Visual Studio theme, as shown in Figure 1.
Being built atop Visual Studio 2010 also means that SSMS 2012 picks up Visual Studio 2010's vastly improved multi-monitor support -- something that I've long awaited (because my desktop sports three monitors). Consequently, my favorite new feature of SSMS is the ability to "tear out" tabs from the main work area and drag them into different monitors or outside of the main IDE. Doing so lets me easily compare scripts or context in one file with the contents of another file without having to toggle back and forth between tabs (and without having to spin up a different instance of SSMS, as I was wont to do previously). Likewise, the ability to "detach" tool windows and position them in other monitors is another huge productivity benefit.
Another subtle productivity benefit that SSMS 2012 picks up is that it finally inherits Visual Studio's Clipboard buffer. This means that you can cycle through previously copied text by holding down the Shift key while pressing Ctrl+V.
An even more powerful productivity benefit that SSMS 2012 sports is the ability to leverage code snippets from within SSMS. This capability is something that has been sorely lacking for those of us addicted to snippets from developer experience within Visual Studio over the plast half-decade. Strangely, though, rather than being keyed off of "mnemonics" as is the case in Visual Studio, SSMS snippets are (by default) injected by means of pulling up a snippets "menu" that can be accessed via the Edit, IntelliSense, Insert Snippet menu option -- or via a similar Surround With menu option. Both of these menu options, of course, can be accessed via hotkeys (Ctrl+K, X and Ctrl+K, S), and the existing library of snippets available is quite large and helpful out of the box.
Initially I was a bit shocked that these snippets don't use SQL Server's age-old template functionality, but it didn't take me long to realize that the parameter-replacement semantics provided by these snippets (in the form of tabbing from one parameter to the next) provide a much better user experience than "old-school" templates. Moreover, although the out-of-the-box snippets that come with SSMS 2012 are great, it doesn't take much energy or effort to customize or create your own snippets (especially if you're using an awesome tool like Snippet Designer).
Furthermore, when it comes to customizing and managing snippets, the Tools, Code Snippets Manager option provides paths to existing snippets along with the option to add or remove snippets as needed. All that Code Snippets Manager is missing is the option to manage shortcuts (or mnemonics); shortcuts are supported, but only if you crack files open manually. Still, SSMS 2012's snippets feature is a significant productivity boon for developers.
As expected, SSMS 2012 continues to deliver the native support for working with SQL Azure databases that debuted with SSMS 2008 R2, although (maybe this is just my imagination) working with SQL Azure databases in SSMS 2012 feels just a tiny bit more responsive than before. Either way, SSMS 2012 sports a few new tasks for managing data-tier applications when you right-click on an Azure database -- so that's a minor improvement as well.

SQL Server 2012 improvements for Visual Studio 2010. As mentioned previously, another significant tooling change for developers is that with SQL Server 2012, BIDS ceases to exist. Of course, BIDS was really never anything more than a lightly "skinned" version of Visual Studio that provided specialized project templates and underlying tooling support for SQL Server Reporting Services (SSRS), SQL Server Integration Services (SSIS), and SQL Server Analysis Services (SSAS). In my experience, BIDS was always a source of unending frustration for developers who wanted to do .NET development and manage any form of BI (or SS*S) projects as well -- simply because of all of the versioning problems that continued to plague BIDS throughout its history. Consequently, one of the things I was most excited about with SQL Server 2012 was that it retired BIDS. This retirement means that it's now possible with SQL Server 2012 to directly create and manage all BI-related projects directly within Visual Studio 2010. It's also worth mentioning that these project types pick up some new UI benefits and tweaks. For example, one of my favorite changes with SQL Server 2012 is that SSIS projects now have a full-blown tab in the .dtsx tab for parameters, as shown in Figure 2. This tab replaces the formerly employed approach, where naturally horizontal editing of parameters was crammed into a Tool Window that was vertical by default.
Although it's nice to finally be able to painlessly open and work with BI projects in Visual Studio 2010, the bad news is that age-old compatibility problems still exist in the sense that if you want support for managing BI-related projects in Visual Studio 2010, you have to uninstall Visual Studio (if it's already installed) and then reinstall it after you install SQL Server 2012 -- which, of course, is beyond lame. That said, an easier way to get BI-related project templates is to just install SSDT, but that currently comes with some drawbacks as well.
SQL Server Data Tools 2012. According to Microsoft, SSDT was effectively designed to replace the SQL Server "Data Dude" SKU (aka Visual Studio Team System 2008 Database Edition) of yore. As such, SSDT provides a number of designers and editing capabilities for working with so-called database projects, where SSDT can help track changes made via designers, and so on. Correspondingly, SSDT also includes schema-comparison tooling and capabilities. A thorough overview of all the features and benefits provided by SSDT is outside the scope of this article. If you're interested in learning more about SSDT, you can find great information and insights about what it does and how it works by visiting the SSDT home page or by visiting the SSDT Team Blog.
Although I've spent a bit of time working with SSDT to "put it through the paces," I must confess that I've never been very excited about Data Dude (not just because of the name), and that lack of enthusiasm now extends to SSDT as well. Stated simply, as a longtime database developer and former production DBA, I'm just not afraid of the complexity associated with database change management, and I can't help but find that SSDT is inadequate for handling changes in the mission-critical environments of my SQL Server consulting clients. Therefore, given that SSDT (somehow) breaks the ability to close documents in SSMS 2012 by middle-clicking, I'd personally take the ability to middle-click my documents closed over all the features and benefits that SSDT provides. Of course, that bug is hopefully only a temporary setback, and I'm sure other developers and DBAs would feel much differently about SSDT. Consequently, SSDT is well worth a further look, because it's a major new feature of SQL Server 2012.

Programmability Enhancements: T-SQL and Engine Improvements

Even as SQL Server 2012's improved tooling and enhanced IDEs provide big productivity wins for developers, SQL Server 2012 also sports a number of programmability enhancements and functions that SQL Server developers will enjoy. SQL Server 2012 packs in a number of great features and capabilities that developers have been requesting for a while now, along with some great surprises that provide some useful new capabilities. Let's take a look at the new programmability features.
T-SQL gets a THROW statement. For SQL Server developers who are familiar with the .NET Framework, the lack of a T-SQL THROW statement has always been a bit strange. Happily, SQL Server 2012 has addressed that lack -- though you'll want to pay attention to the Remarks section of SQL Server Books Online ( BOL) for this new feature because there are a number of limitations as to how this statement can be used. Likewise, as cool as this new feature is, just remember that RAISERROR (despite its archaic spelling) still provides a number of powerful features that THROW (and PRINT) simply don't offer.
T-SQL finally supports built-in pagination. I still remember how disappointed I was more than a decade ago to learn that SQL Server didn't provide built-in support for pagination as MySQL did. Happily though, SQL Server 2012 finally introduces full-blown, first-class support within T-SQL for pagination, as shown in Figure 3. Note, too, that pagination is technically a feature or argument of the ORDER BY clause -- and that Microsoft actually recommends using OFFSET and FETCH as a replacement for TOP.
-- Create and populate a simple table -- full of 'contact' information: CREATE TABLE dbo.Contacts (         ContactId int IDENTITY(1,1) NOT NULL,         FirstName varchar(60),         LastName varchar(60),         Phone varchar(60) ); INSERT INTO dbo.Contacts SELECT name, name, name FROM master.dbo.spt_values; -- Skip 300 rows 'into' the results and -- take the next 10 records: SELECT ContactId, FirstName, LastName, Phone FROM dbo.Contacts ORDER BY ContactId         OFFSET 300 ROWS         FETCH NEXT 10 ROWS ONLY;
Support for sequences. Another great new feature that SQL Server 2012 provides (which Oracle has had for nearly forever) is support for sequences. A sequence can best be described as being a bit like an IDENTITY "object" because it behaves just like an IDENTITY column without actually being a column. Developers can create sequences, query them for one or more IDs (which are returned in sequence), and then do whatever they want with those supplied IDs prior to INSERTing them into a table that needs a unique, sequentially incrementing, identity value, as shown in Figure 4.
-- Create a simple sequence: CREATE SEQUENCE dbo.ExampleSequence AS int         START WITH 1 INCREMENT BY 1; -- Create a simple/test table, too: CREATE TABLE dbo.SequentialTable (         SampleId int NOT NULL,         SampleValue nvarchar(40) NOT NULL ); -- Sample/example of easiest way to grab value: SELECT NEXT VALUE FOR dbo.ExampleSequence; -- Now copy 'next' value (2) into a parameter: DECLARE @NextSequence int SELECT @NextSequence = NEXT VALUE         FOR dbo.ExampleSequence; -- And use it for an INSERT. -- But in non-trivial examples - you could use it for FK inserts -- or other operations as well BEFORE trying the following INSERT. INSERT INTO dbo.SequentialTable (SampleId, SampleValue) VALUES (@NextSequence, '@NextSequence will have a value of 2.'); SELECT * FROM dbo.SequentialTable; GO
One of the big benefits of sequences is that developers can use them in much the same way as they use GUIDs today, but without the type of performance issues associated with the ugly fragmentation that ensues when using unique identifiers as a clustered index key. In addition to that benefit, sequences open up other very cool possibilities by virtue of some of their extended capabilities, such as the ability to CYCLE or "repeat" sequence values after they hit a specified maximum identity value. SQL Server 2012 also provides a number of options for intelligently working with and querying sequence metadata.
Metadata discovery improvements. Speaking of metadata, SQL Server 2012 also provides drastically improved support for metadata discovery, which makes it much easier for developers to determine the shape of projected output from queries, sprocs, views, and other objects that can be queried. Although many developers will never use this functionality, I can't help but think of how useful it will be for developers creating micro ORMs (which I suspect will become much more popular as developers tire of the bloat and overhead associated with Entity Framework).
Projection redirection and the WITH RESULT SETS argument. Another great new feature of SQL Server 2012 that developers will find useful is the ability to "re-project" or change the output of stored procedures by specifying new column names, casts, and other sorts of operations when executing stored procedures by means of the WITH RESULT SETS clause (see Figure 5). This feature is something that will be very valuable for helping to assist with versioning concerns and considerations in larger and more complex applications and deployments.
-- An INSANELY simple sample sproc: CREATE PROC dbo.TestProc         @input1 int,         @input2 varchar(20) AS         SET NOCOUNT ON         SELECT @input1 AS [Output1], @input2 [Output2]         RETURN 0 GO -- Now transform the output/projection/results: EXEC dbo.TestProc 292, 'This is Some Text' WITH RESULT SETS ( ([Column 1] int, [Column 2] varchar(20)) );

Programmability Enhancements: New T-SQL Functions

As outlined in BOL, SQL Server 2012 introduces a bevy of new functions that developers can use. Here are my thoughts about a few of them.
FORMAT(). In my mind, this single function is one of the hands-down best new features of SQL Server 2012, simply because the functionality that it provides has been so sorely needed for so long. And for .NET developers, the immediate and obvious benefits of this new function should be readily apparent just by looking at Figure 6. Another thing that I like about the new FORMAT() function is that it represents an additional influx of CLR functionality directly into T-SQL -- something that I hope to see more of in the future.
SELECT         FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date],         FORMAT(GETDATE(), 'yyyy-MM-dd hh:mm:ss') AS [Full ISO],         FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-hand Date (EN)],         FORMAT(GETDATE(), 'MMMM dd, yyyy', 'fr-FR') AS [French Date],         FORMAT(22.7, 'C', 'en-US') AS [US Currency],         FORMAT(22.7, 'C', 'en-GB') AS [UK Currency],         FORMAT(99 * 2.226, '000.000') AS [Padded Decimal],         FORMAT(12345678, '0,0') AS [Finally: Commas in Large Numbers] ;
CHOOSE(). With the CHOOSE() function, you can quickly and easily translate an integer value into an array of corresponding string values, as shown in Figure 7.
-- CHOOSE() makes these easy to 'format' in ad hoc -- reports. The following returns 'Male' or position -- number 2 in the 1-based (i.e., non-0 based) array. SELECT CHOOSE(2, 'Female','Male', 'Unknown') AS [Gender]; -- Just be aware that hard-coding values into -- 'permanent' code can/will cause problems long term. -- The following returns NULL - as 4 exceeds array or is not found. SELECT CHOOSE(4,'Female','Male','Unknown') AS [x];
Personally, I think that the new CHOOSE() function is a mixed blessing. On the one hand, this function can and will make minor "formatting" and reporting needs much easier to handle. On the other hand, it doesn't take much thought at all to see how the use of CHOOSE() within code can and will lead to "magic numbers" programming within code and how it will lead to versioning problems and issues that will ultimately cause this function to generate all sorts of problems over the long term.
Conversion functions and date and time functions. For developers familiar with the .NET Framework, T-SQL's new TRY_CONVERT() and TRY_PARSE() functions will be a welcome new addition, along with a host of new Date and Time functions (of varying benefit and usefulness). All told, SQL Server 2012 does a great job of introducing an assortment of new functions that will make programing T-SQL that much easier.

Engine Enhancements That Benefit Developers

Although it's a common or even logical assumption that enhancements to the core SQL Server engine are things that typically excite DBAs, that doesn't mean that many of these benefits can't translate into tangible improvements that will aid developers. As such, SQL Server 2012 actually ships with a number of programmability enhancements that it lists in the "What's New" section of BOL with descriptions about new developments for the SQL Server Engine. These enhancements include some great new improvements to full-text indexing, enhanced spatial features, and the addition of FILETABLE functionality that extends existing FILESTREAM storage capabilities.
But, above and beyond these obvious engine enhancement benefits, there are also a couple of other big benefits that aren't as obvious to spot: partially contained databases and a new version of SQL Server Express.
Contained databases. With SQL Server 2012, contained databases provide a means for effectively decoupling SQL Server databases (and their users, collations, and other assets) from the underlying SQL Server instance itself. Stated differently, contained databases are much more "portable" in the sense that they can be easily moved from one server to another -- without worries about orphaned users and other issues that have typically made moving databases problematic. Thus, not only are contained databases a big win in corporate environments where DBAs need to shunt databases around for load-balancing purposes, they're also a huge win for ISVs (and developers) who want to more easily copy, move, or deploy databases with their software. Similarly, for web developers who rely on SQL Server as a back-end database, contained databases help make developers less dependent on hosting platforms as their databases become more portable -- another huge win.
Better yet, since there remains a fine line between what kind of code and operations are server-dependent and what kinds of programming and operations can be isolated into contained databases, Microsoft has done a fantastic job of making it easy to query specialized dynamic management views (DMVs) that will let developers (and DBAs) know how "contained" or portable their databases are. As such, my anticipation is that contained databases are not only one of the biggest wins for developers in SQL Server 2012 but also a key component in eventually helping Microsoft push SQL Azure as a database-hosting platform.
SQL Server 2012 Express LocalDB. Another great feature that SQL Server 2012 offers for developers is a new lightweight installation of SQL Server Express. This new version of SQL Express, SQL Server 2012 Express LocalDB, makes ISV and other forms of "embedded" SQL Server deployments much easier to tackle by means of allowing a much more streamlined installation process along with the ability to let SQL Server run in-process with applications. Best of all, documentation for this new developer-friendly version of SQL Server is included in BOL -- and the price remains, of course, free.

Discontinued and Deprecated Features

Of course, with every new release of SQL Server, there are also a few features and bits of syntax that are either removed outright or are slated for later removal. Happily, with SQL Server 2012, the list of deprecated and removed features is relatively small. This, in turn, means that SQL Server 2012 does a great job of providing developers with new features -- with very little worry or concern for negative problems of backward compatibility.

SQL Server 2012 T-SQL at a Glance: New and Enhanced Functions



SQL Server 2012 T-SQL at a Glance: New and Enhanced Functions
SQL Server 2012 (formerly code-named Denali) CTP3 adds several new functions that will make our lives a little bit easier in several areas: conversion and parsing, date and time, logical, string manipulation and math. Some of the functions are objectively very important and convenient to have, whereas others are important because they enable easier migration from other platforms, e.g., Microsoft Access. I’ll describe the new functions according to their categories.
For sample data I used a database called TSQL2012.
Conversion and Parsing
New functions in this category: TRY_CONVERT, PARSE and TRY_PARSE.
TRY_CONVERT
The TRY_CONVERT function is one that many developers have been hoping to get for a long time. It works pretty much like the existing CONVERT function, only when the input value isn’t convertible, instead of generating an error, the function returns a NULL. Here’s an example, followed by its output:

SELECT TRY_CONVERT(INT, 100) AS try1, TRY_CONVERT(INT, 'abc') AS try2;



try1        try2

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

100         NULL
Like the CONVERT function, also TRY_CONVERT supports a third style argument where relevant.
One classic case where this function can be useful is in dynamic schema scenarios. Each row represents a single entity, attribute, value (EAV), where the values are stored as character strings. But even though the values are all stored in a character string column, each attribute conceptually can have a different type (number, data, etc.). You have the conceptual type of the value stored in its own column (call it thetype). Suppose you attempt to filter only attributes representing integers, convert to an INT type, and then do something with the result. So your filter looks something like this:
WHERE thetype = 'INT' AND CAST(val AS INT) > 10
I get into the details of why this form can actually fail in SQL Server in the second part of a two part series in my column titled T-SQL String Manipulation Tips and Techniques. For the purposes of this blog, suffice to say that this form can fail on a conversion error because SQL Server may actually attempt to handle the conversion before evaluating the left expression. With TRY_CONVERT you can easily avoid such failures using the following form:
WHERE thetype = 'INT' AND TRY_CONVERT(INT< val) > 10
Would be nice if SQL Server added in the future also a TRY_CAST function where the style isn’t relevant; perhaps even a more general TRY_THIS function that would work with any expression that generates a trappable error. For example, why not allow TRY_THIS(col1 / col2), and in case of an error like divide-by-zero simply return a NULL?
PARSE
The PARSE function in essence does a conversion of an input string to the target type, but unlike CAST and CONVERT, it supports an optional USING clause indicating the culture. The culture is any valid culture supported by the .NET framework. If a culture isn’t specified, SQL Server will rely on the current session’s effective language. One of the benefits in this function when an explicit culture is used is that it allows you to phrase the values in a form that is based on your culture’s conventions, without worrying about the language of the user running your code.
Here’s an example parsing strings as dates, in one case using US English culture, and in the other, Japanese:
SELECT PARSE('7/17/2011' AS DATE USING 'en-US') AS dt1, PARSE('2011/7/17' AS DATE USING 'ja-JP') AS dt2;

dt1        dt2

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

2011-07-17 2011-07-17
TRY_PARSE
The TRY_PARSE to PARSE is like TRY_CONVERT is to CONVERT; namely, TRY_PARSE does the same as PARSE, only when the input isn’t converted to the target type, instead of generating an error, the function returns a NULL. For example, the following invocation of PARSE fails:
SELECT PARSE('7/17/11' AS DATE USING 'ja-JP') AS dt;

Msg 9819, Level 16, State 1, Line 1

Error converting string value '7/17/11' into data type date using culture 'ja-JP'.
A similar attempt with TRY_PARSE returns a NULL:
SELECT TRY_PARSE('7/17/11' AS DATE USING 'ja-JP') AS dt;

dt

----------

NULL
Date and Time
New functions in this category: EOMONTH,  DATEFROMPARTS, DATETIME2FROMPARTS, DATETIMEFROMPARTS, DATETIMEOFFSETFROMPARTS, SMALLDATETIMEFROMPARTS and TIMEFROMPARTS.
EOMONTH
The EOMONTH function returns the end of month date corresponding to the input date and time value, with the time set to midnight, retaining the time zone if it exists. Here’s an example I ran on September 28th, 2011, invoking EOMONTH with SYSDATETIME as input:
SELECT EOMONTH(SYSDATETIME()) AS endofmonth;

endofmonth

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

2011-09-30 00:00:00.00
If the input type is one of the supported date and time datatypes, the type of the output is that of the input. Otherwise, as long as the input is convertible to a date and time type, the type of the output is DATETIME2(7).
It’s important to note is that the function doesn’t return the last possible point in time for the respective month based on the type of the input, rather midnight of the last day of the month. As long as the values stored in the data have only the date, or use only midnight, it is actually quite convenient to use this function. As an example, the following query returns orders placed on the last day of the month:
SELECT orderid, orderdate, custid, empid

FROM Sales.Orders

WHERE orderdate = EOMONTH(orderdate);
Here I’m relying on the fact that all order dates are stored with midnight in the time. If that’s not a guarantee, and the time can be other than midnight, to address the task correctly you would need to express the filter as a range, like so:
SELECT orderid, orderdate, custid, empid

FROM Sales.Orders

WHERE orderdate >= EOMONTH(orderdate)

  AND orderdate < DATEADD(day, 1, EOMONTH(orderdate));
Surprisingly, SQL Server Denali CTP3 doesn’t also support functions for end of other periods (e.g., quarter, year), or the beginning of any period. For now, you have to roll your own. This reminds me of an amusing, though very practical, suggestion, by my friend and colleague Gianluca Hotz when he learned that there’s no support for other similar functions. He suggested creating a function called ENDOFTIME that will accept the period (e.g., MONTH, QUARTER, YEAR) as another input, and return the end of that period. Similarly a function called BEGINNINGOFTIME or STARTOFTIME could accept a value and a period, and return the beginning of that period.
%FROMPARTS
For each date and time data type, SQL Server Denali provides a FROMPARTS function that allows constructing a value of this type from integer parts. This is useful in general, but also important for migrations from environments like Excel, Access and others that support such functionality.
Here’s sample code constructing a value of each of the date and time types:
SELECT

  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_FROMPARTS    

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

2012-02-12     2012-02-12 13:30:05.00 2012-02-12 13:30:05.997



DATETIMEOFFSET_FROMPARTS           SMALLDATETIME_FROMPARTS TIME_FROMPARTS

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

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

DATE_FROMPARTS DATETIME2_FROMPARTS    DATETIME_FROMPARTS     
-------------- ---------------------- -----------------------
2012-02-12     2012-02-12 13:30:05.00 2012-02-12 13:30:05.997

DATETIMEOFFSET_FROMPARTS           SMALLDATETIME_FROMPARTS TIME_FROMPARTS
---------------------------------- ----------------------- ----------------
2012-02-12 13:30:05.0000001 -08:00 2012-02-12 13:30:00     13:30:05.0000001
Logical
Functions in this category: CHOOSE and IIF.
The IIF and CHOOSE functions are another pair of functions that Denali supports to allow easier migration from environments running Access.
CHOOSE
The CHOOSE function accepts an integer input followed by a list of values of any data type, and returns as output the value from the list in the position indicated by the first input. Here’s an example for using the function:
SELECT CHOOSE(1, 'a', 'b', 'c') AS first, CHOOSE(2, 'a', 'b', 'c') AS second;



first second

----- ------

a     b
Of course you can implement similar logic very easily using the standard CASE expression, but as mentioned, the point is making migrations from Access smoother.
IIF
The IIF function is another function Access supports. It accepts as first input a predicate, as second input an expression to return in case the predicate is true, and as third input an expression to return in case the input is false or unknown. Here’s an example for using the function:
SELECT IIF(1 = 2, 'a', 'b') AS iif_result;



iif_result

----------

b
Just like with CHOOSE, it’s very simple to implement the IIF logic with a standard CASE expression, but the point was making Access migrations easier.
String Manipulation
New functions in this category: CONCAT and FORMAT.
CONCAT
The CONCAT function concatenates the input values into a single result string. If you’re wondering what’s the reason for adding such a function when T-SQL already has a concatenation operator (+), there are two main reasons:
1. The concatenation operator + yields a NULL on NULL input. The CONCAT function converts NULL inputs to empty strings before concatenation. Of course you can get by using the COLAESCE function, replacing a NULL input with an empty string, but this makes the code messy.
2. Other platforms support the CONCAT function, and adding such support in SQL Server makes migration from those platforms easier.
As an example, consider the location attributes country, region and city, of customers. The region attribute simply isn’t applicable in some locations, in which case it is set to NULL. You want to generate a single string of all three location attributes, separating the applicable ones by commas. With the CONCAT function it’s very simple:
SELECT custid, city, region, country,

  CONCAT(city, ', ' + region, ', ' + country) AS location

FROM Sales.Customers

WHERE custid > 85;

custid      city            region          country         location

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

86          Stuttgart       NULL            Germany         Stuttgart, Germany

87          Oulu            NULL            Finland         Oulu, Finland

88          Resende         SP              Brazil          Resende, SP, Brazil

89          Seattle         WA              USA             Seattle, WA, USA

90          Helsinki        NULL            Finland         Helsinki, Finland

91          Warszawa        NULL            Poland          Warszawa, Poland
Notice that when the region attribute was applicable it was made part of the result string, and when it wasn’t, the NULL was simply replaced with an empty string.
FORMAT
The FORMAT function allows you to format an input value to a character string based on a .NET format string. You can optionally indicate a culture when relevant. As an example, the following code formats the result of the GETDATE() function using the format string 'd' (meaning, short date pattern), in one case using US English culture, and in another Japanese:
SELECT FORMAT(GETDATE(), 'd', 'en-US') AS us, FORMAT(GETDATE(), 'd', 'ja-JP') AS jp


us          jp

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

9/28/2011   2011/09/28

This function allows a lot of flexibility in formatting inputs. For example, the following code formats product IDs as 10-digit strings with leading zeros:
SELECT FORMAT(productid, '0000000000') AS strproductid, productname

FROM Production.Products;


strproductid  productname

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

0000000058    Product ACRVI

0000000009    Product AOZBW

0000000051    Product APITJ

0000000045    Product AQOKR

0000000033    Product ASTMN

...
Note, though, that the function relies on .NET for the purposes of formatting, which has overhead. Compared, for example, with functions like STR, the FORMAT function is much slower.
Math
Enhanced function in this category: LOG.
LOG
So far SQL Server supported two functions that compute logarithms: LOG (for natural logarithm) and LOG10 (for logarithm with a base of 10). If you wanted to compute a logarithm with any other base, you had to do it mathematically, using a log with a supported base, dividing the log of the input value by the log of the input base. For example, to compute the logarithm of 256 using the base 2, you could use the following expression:
SELECT LOG(256) / LOG(2);
SQL Server Denali enhances the LOG function by supporting a second argument representing the base. So to achieve the same thing in Denali, you simply use the following expression:
SELECT LOG(256, 2);
Now life is good; of course, it could be made event better with support for TRY_THIS, ENDOFTIME and BEGINNINGOFTIME. :)
Cheers,
BG
This article we will focus on the T-SQL Enhancements in SQL Server 2011.
The main new TSQL features in SQL Server 2012 are:
  1. WITH RESULT SETS
  2. OFFSET AND FETCH
  3. THROW in Error handling
  4. SEQUENCE

WITH RESULT SETS

This is a good feature provided with the execution of a stored procedure.
Legacy method
In earlier versions of SQL server when we wished to change a  column name or datatype in the resultset of a stored procedure, all the references needed to be changed. There was no simple way to dump the output of a stored procedure without worrying about the column names and data types.
 2012 Method
With SQL Server 2012, the new WithResultsSet feature avoids the requirement to change the stored procedure in order to change the column names in a resultset.
For example :
CREATE PROCEDURE Denali_WithResultSet
AS
BEGIN
       SELECT 1 as No,’Tsql’ Type, ‘WithResultSet’ AS Feature UNION ALL
       SELECT 2 as No,’Tsql’ Type, ‘Throw’ AS Feature UNION ALL
       SELECT 3 as No,’Tsql’ Type, ‘Offset’ AS Feature UNION ALL
       SELECT 4 as No,’Tsql’ Type, ‘Sequence’ AS Feature
END
GO
EXEC Denali_WithResultSet
WITH RESULT SETS
(
       (      No int,
              FeatureType varchar(50),
              FeatureName varchar(50)
       ) 
)
http://c3154802.r2.cf0.rackcdn.com/article_images/SQLDenali_Article_files/image002.jpg
The WithResultsSet option after the Exec statement conatins the resultset in (…) brackets. Here, we can change the column name and datatype according to our needs,  independent of what is column name returned in the resultset. In the above example ‘Type’ is changed to ‘FeatureType’ and ‘Feature’ is changed to ‘FeatureName’. This can be helpful for using an appropriate datatype while showing the resultset.
This feature will be especially helpful when executing a stored procedure in SSIS tasks. While executing any stored procedure in OLEDB Source, it will be now possible to execute the procedure with the required column names and datatypes.
Continues…