Friday, June 15, 2012

Create and Alter Stored Procedures


(This is part of the Study Guide series, 70-457)

Microsoft’s Measured Skill description: This objective may include but is not limited to: write a stored procedure to meet a given set of requirements; branching logic; create stored procedures and other programmatic objects; techniques for developing stored procedures; different types of stored procedure results; create a stored procedure for data access layer; program stored procedures, triggers, and functions with T-SQL

What I see:
·         stored procedure results
·         create stored procedures

Stored Procedure Results
                I go into quite a bit detail about the difference types of stored procedure results, and returning data to the calling code in this SQL Salt blog post.  In summary, stored procedures have a few ways of returning data, but often times there are different requirements to use each method, such as returning a result set, or returning execution status (success or failure).  To see examples and a fuller explanation, read the linked blog post.

Create Stored Procedures
                Again, this was covered in the same SQL Salt blog post as above.  Not much to it, but there are a lot of “gotchas” that could arise.  Read the blog post, but also see BOL for corner-cases that aren’t always widely known.

References

If there are any comments, questions, issues, or suggestions please feel free to leave a comment below or email me at sqlsalt@gmail.com.

Implement Data Types


(This is part of the Study Guide series, 70-457)

Microsoft’s Measured Skill description: This objective may include but is not limited to: use appropriate data; understand the uses and limitations of each data type; impact of GUID (newid, newsequentialid) on database performance, when to use which data type for columns

What I see:
·         appropriate data types
·         NEWID() vs. NEWSEQUENTIALID()

Appropriate Data Types
                This is one of those can’t-really-explain-it-in-a-blog-post topics, but I think what Microsoft is getting at here is that you should know the limitations (for data storage as well as storage consumption) of the many data types that SQL Server uses.  For instance, know the difference (precision, storage) between datetime and datetime2, and when to use one or the other.  See BOL for a refresher on the data types.

NEWID() vs. NEWSEQUENTIALID()
                I wrote a blog post on this exact topic.  For extensive information, review that.  But in summary, NEWID() does not ensure a sequentially generated GUID, and that is a bad candidate for a clustered index key.  This could lead to high amounts of page splits and index fragmentation.  NEWSEQUENTIALID() solves that problem by ensuring sequential identifiers when called.

References
·         BOL reference on Data Types

If there are any comments, questions, issues, or suggestions please feel free to leave a comment below or email me at sqlsalt@gmail.com.

Thursday, June 14, 2012

Implement Sub-Queries


(This is part of the Study Guide series, 70-457)

Microsoft’s Measured Skill description: This objective may include but is not limited to: identify problematic elements in query plans; pivot and unpivot; apply operator; cte statement; with statement

What I see:
·         pivot and unpivot
·         APPLY operator
·         CTEs

PIVOT and UNPIVOT
                In my opinion the best resource for learning and reviewing PIVOT and UNPIVOT is BOL.  They have written a great explanation with very helpful examples.  Please see this reference for further reading.

APPLY Operator
                The APPLY operator is used with a table-valued function to pass parameters to the TVF and these are then “applied” to the result set.  Below shows an example of this:

use MeasureMySkills;
go

create table NumbersTable
(
       id int identity(1, 1) not null,
       MyNumber int not null
);
go

insert into NumbersTable(MyNumber)
values
       (3),
       (7),
       (12),
       (5),
       (93),
       (132);
go

create function AddMore
(
       @original_num int,
       @add_by int
)
returns table
as
       return
       (
              select
                     @original_num + @add_by as NewNum
       )
go

select
       nt.id,
       nt.MyNumber,
       ao.NewNum
from NumbersTable nt
cross apply AddMore(nt.MyNumber, 27) ao;

As you can see in the above example, by using the CROSS APPLY clause with the AddMore() TVF, the result set now contains the additional column NewNum with the calculated values from the function.

CTEs
                A Common Table Expression (CTE) is a temporary result set that has the scope of and can be used for a single, subsequent DML statement.  Its definition starts out with the WITH keyword.  It is commonplace to put a semi-colon in front of the WITH, as SQL Server needs to know it’s not part of a previous statement.

use AdventureWorks2012;
go

;with PersonCTE as
(
       select
              BusinessEntityID,
              FirstName,
              LastName,
              EmailPromotion
       from Person.Person
)
select
       EmailPromotion,
       count(*) as EmailPromoCount
from PersonCTE
group by EmailPromotion;

References
·         BOL reference on Using APPLY

If there are any comments, questions, issues, or suggestions please feel free to leave a comment below or email me at sqlsalt@gmail.com.

Wednesday, June 13, 2012

Query Data by Using SELECT Statements


(This is part of the Study Guide series, 70-457)

Microsoft’s Measured Skill description: This objective may include but is not limited to: use the ranking function to select top(X) rows for multiple categories in a single query; write and perform queries efficiently using the new code items such as synonyms and joins (except, intersect); implement logic which uses dynamic SQL and system metadata; write efficient, technically complex SQL queries, including all types of joins versus the use of derived tables; determine what code may or may not execute based on the tables provided; given a table with constraints, determine which statement set would load a table; use and understand different data access technologies; CASE versus ISNULL versus COALESCE

What I see:
·         ranking functions
·         except and intersect
·         data access technologies
·         CASE vs. ISNULL vs. COALESCE

Ranking Functions
                There are four ranking functions available in SQL Server:  RANK, DENSE_RANK, ROW_NUMBER, and NTILE.

As per BOL, the RANK function “returns the rank of each row within the partition of a result”:

use MeasureMySkills;
go

create table RankingTable
(
       id int identity(1, 1) not null,
       IntValue int not null
);
go

insert into RankingTable(IntValue)
values
       (16),
       (17),
       (17),
       (19),
       (26),
       (25),
       (26),
       (26),
       (30);

select
       id,
       IntValue,
       rank() over
       (
              order by IntValue
       ) as Rank
from RankingTable;

As you can see from the above result, ties are the same rank but then subsequent rank values reflect the gap caused by the ties.  If you want to fill those gaps (i.e. have a “dense” ranking), use the DENSE_RANK function:

select
       id,
       IntValue,
       dense_rank() over
       (
              order by IntValue
       ) as DenseRank
from RankingTable;

Another common ranking function is ROW_NUMBER.  This ranking function will assign a sequential, non-duplicated “row number” to the result set (very handy for deleting duplicate data through the use of the windowing PARTITION BY clause):

select
       id,
       IntValue,
       row_number() over
       (
              order by IntValue
       ) as RowNumber
from RankingTable;

And the last ranking function is NTILE.  This ranking function breaks the windowed data into the specified number of groups:

select
       id,
       IntValue,
       ntile(3) over
       (
              order by IntValue
       ) as NTile
from RankingTable;

EXCEPT and INTERSECT
                These two operators return the same distinct rows from two queries (INTERSECT) or missing distinct rows from first query that aren’t in the second query (EXCEPT).  Below shows examples of this output:

create table IntersectExceptTbl1
(
       MyInt int not null,
       MyString nvarchar(128) not null
);
go

create table IntersectExceptTbl2
(
       MyInt int not null,
       MyString nvarchar(128) not null
);
go

insert into IntersectExceptTbl1(MyInt, MyString)
values
       (1, 'a'),
       (2, 'b'),
       (3, 'c'),
       (4, 'd'),
       (5, 'e');

insert into IntersectExceptTbl2(MyInt, MyString)
values
       (1, 'a'),
       (6, 'b'),
       (3, 'c'),
       (4, 'f'),
       (5, 'e');

select *
from IntersectExceptTbl1
intersect
select *
from IntersectExceptTbl2;

/* RESULT SET (INTERSECT)
MyInt  MyString
1             a
3             c
5             e             */

select *
from IntersectExceptTbl1
except
select *
from IntersectExceptTbl2;

/* RESULT SET (EXCEPT)
MyInt  MyString
2             b
4             d             */

Data Access Technologies
                For more information, please see this MSDN reference on the Data Access Technologies Road Map.  It is worth familiarizing yourself with the most commonly-used methods.

CASE vs. ISNULL vs. COALESCE
                Choosing between CASE, ISNULL, and COALESCE just comes down to what’s the best tool for the given task.  CASE is typically used for relatively complex conditional logic that COALESCE can’t encompass (for instance, not driven by NULL).  COALESCE is really just a restricted and abbreviated CASE expression.  ISNULL is simply used to return either the first parameter’s value, or if that’s NULL then it’ll return the second.  This is great for ensuring that NULL isn’t passed to aggregating functions, or any other time that NULL is less than desired.

References
·         BOL reference on RANK
·         BOL reference on DENSE_RANK
·         BOL reference on ROW_NUMBER
·         BOL reference on NTILE
·         BOL reference on ISNULL
·         BOL reference on CASE
·         BOL reference on COALESCE

If there are any comments, questions, issues, or suggestions please feel free to leave a comment below or email me at sqlsalt@gmail.com.