Posts belonging to Category T-SQL



PASSMN July Meeting Today

Minnesota SQL Server Users Group

Don’t forget the July PASSMN meeting is today.  We have Itzik Ben-Gan (blog) coming in to talk about some query tuning tips.

Here are the meeting details…

Date and  Time:

July 20, 2010, 5:00 PM CST

Location:

8300 Norman Center Drive, 9th Floor, Bloomington, MN  55437 (map)

Live Meeting

Agenda:

5:00 –5:15 : Announcements
5:15 –5:25 : Sponsor
5:25 –6:45 : Query Tuning Tips (Itzik)
6:45 –7:00 : Survey Collection and Giveaways

Presentation:

Query Tuning Tips

Given a SQL Server querying problem there’s much that you can do to enable a good performing solution. Tuning involves arranging an optimal physical environment, e.g., by creating supporting indexes, as well as writing the query in a way that it would get an optimal execution plan. Many factors can affect the efficiency of the solution including the availability of indexes, data distribution and density, and others. In different scenarios, a different solution could be the most efficient for the same querying problem. Query tuning could be considered an art. This session will provide various tips to do efficient query tuning and demonstrate those through specific tuning examples.

Itzik Ben-Gan is a Mentor and Co-Founder of Solid Quality Mentors. A SQL Server Microsoft MVP (Most Valuable Professional) since 1999, Itzik has delivered numerous training events around the world focused on T-SQL Querying, Query Tuning and Programming. Itzik is the author of several books including Microsoft SQL Server 2008: T-SQL Fundamentals, Inside Microsoft SQL Server 2008: T-SQL Querying and Inside Microsoft SQL Server 2008: T-SQL Programming. He has written many articles for SQL Server Magazine as well as articles and whitepapers for MSDN. Itzik’s speaking activities include TechEd, DevWeek, SQLPASS, SQL Server Magazine Connections, various user groups around the world, and Solid Quality Mentors’ events to name a few. Itzik is the author of Solid Quality Mentors’ Advanced T-SQL Querying, Programming and Tuning and T-SQL Fundamentals courses along with being a primary resource within the company for their T-SQL related activities

PASSMN July Meeting Next Week

Minnesota SQL Server Users Group

The July PASSMN meeting is is coming up next week.  If you’ve not registered now’s a great time to get your RSVP in.  We have Itzik Ben-Gan (blog) coming in to talk about some query tuning tips.

Here are the meeting details…

Date and  Time:

July 20, 2010, 5:00 PM CST

Location:

8300 Norman Center Drive, 9th Floor, Bloomington, MN  55437 (map)

Live Meeting

Agenda:

5:00 –5:15 : Announcements
5:15 –5:25 : Sponsor
5:25 –6:45 : Query Tuning Tips (Itzik)
6:45 –7:00 : Survey Collection and Giveaways

Presentation:

Query Tuning Tips

Given a SQL Server querying problem there’s much that you can do to enable a good performing solution. Tuning involves arranging an optimal physical environment, e.g., by creating supporting indexes, as well as writing the query in a way that it would get an optimal execution plan. Many factors can affect the efficiency of the solution including the availability of indexes, data distribution and density, and others. In different scenarios, a different solution could be the most efficient for the same querying problem. Query tuning could be considered an art. This session will provide various tips to do efficient query tuning and demonstrate those through specific tuning examples.

Itzik Ben-Gan is a Mentor and Co-Founder of Solid Quality Mentors. A SQL Server Microsoft MVP (Most Valuable Professional) since 1999, Itzik has delivered numerous training events around the world focused on T-SQL Querying, Query Tuning and Programming. Itzik is the author of several books including Microsoft SQL Server 2008: T-SQL Fundamentals, Inside Microsoft SQL Server 2008: T-SQL Querying and Inside Microsoft SQL Server 2008: T-SQL Programming. He has written many articles for SQL Server Magazine as well as articles and whitepapers for MSDN. Itzik’s speaking activities include TechEd, DevWeek, SQLPASS, SQL Server Magazine Connections, various user groups around the world, and Solid Quality Mentors’ events to name a few. Itzik is the author of Solid Quality Mentors’ Advanced T-SQL Querying, Programming and Tuning and T-SQL Fundamentals courses along with being a primary resource within the company for their T-SQL related activities

Please RSVP here if you will be attending in person, this helps us understand how many people to tell the sponsor to get food for.

Webcast Today – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter later today starting at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

July PASSMN Meeting Announced

Lego DeadlockSometimes when we are putting together the user group meetings things change.  Opportunities arise and we get a chance to take a cool meeting and turn it into a great meeting.  That happened with this months meeting and it’s going to be great.

A couple things are different for this month… time and topic.  This month instead of meeting at 3:00 PM we are meeting at 5:00 PM.  And the reason for the change is that we have Itzik Ben-Gan (blog) stopping by for a presentation.

The Presentation

This month he’ll be teaching a course at Benchmark Learning.  His course is Advanced T-SQL Querying, Programming and Tuning for SQL Server 2005 & 2008.  If you want more than what you suspect will be at the meeting, then this class is for you.

What can you suspect will be at the meeting this month?  Well, how about this?

Query Tuning Tips

Given a SQL Server querying problem there’s much that you can do to enable a good performing solution. Tuning involves arranging an optimal physical environment, e.g., by creating supporting indexes, as well as writing the query in a way that it would get an optimal execution plan. Many factors can affect the efficiency of the solution including the availability of indexes, data distribution and density, and others. In different scenarios, a different solution could be the most efficient for the same querying problem. Query tuning could be considered an art. This session will provide various tips to do efficient query tuning and demonstrate those through specific tuning examples.

Pretty cool stuff, eh?

And the Rest of the Details…

This month’s meeting sponsor is Digineer.  They’ll be providing the food and beverages.  Digineer happens to be my employer and if you’re local and looking for a company with talent and skill this is a good place to look.

Date: July 20, 2010
Time: 5:00 PM – 7:00 PM
Location: 8300 Norman Center Drive, 9th Floor, Bloomington, MN  55437
Live Meeting

The all important RSVP link – please do RSVP so that we’ll have enough food for the event.

Webcast Next Week – Performance Impacts Related to Different Function Types

I’ll be speaking for the SQL PASS Performance Virtual Chapter next week.  It’ll be on July 6 at 12 PM Eastern time.  The topic will be Performance Impacts Related to Different Function Types.  The abstract for the event is the following:

User defined functions provide a means to encapsulate business logic in the database tier.  Often the purpose of the encapsulation is to provide standard method access segments of data within the database.  Unfortunately, not all methods of creating user defined functions are equal.  In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Goals:

  • Identify purposes for creating user defined functions
  • Discuss the types of user-defined functions
  • Demonstrate performance impact in selecting different types of functions

You can get to the event here.

Doing Something About Auto Generated Names

Zombie Apocafest 2009 - Shaun & EdI like my name.  It provides a point of reference to who I am.  If I am at work and someone calls for “Jason Strate”… that’s me.  If I am at home, the same thing can happen and I still know that it’s me.  I know that no matter where I am, my name will be a constant and it means something when it is called.  Hopefully, it doesn’t mean “late to dinner”.

This same principle applies to the tables and the objects related to those tables.  We give that table a name in the development environment, maybe it’s called “ZombieBaconUnicorn”.  We expect that it will be called “ZombieBaconUnicorn”.  Unfortunately, this doesn’t always ring true with other database objects related to tables; such as Primary Keys and Defaults Constraints.

Random Naming

There are multiple ways to create Primary Key and Default Constraints and they don’t all have an implied name.  Take for instance the following script, what would you assume the names of the Primary Key and Default Constraints would be?

CREATE TABLE dbo.RandomPKandDC
(
RandomPKandDCID int IDENTITY(1,1) PRIMARY KEY CLUSTERED
,Column1 datetime DEFAULT(GETDATE())
)

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.RandomPKandDC')

Did you guess the following names?

image

No?!  Run it on you machine, you’ll get your own unique names.

Non-Random Naming

Getting around the random naming is pretty simple.  Below I’ll would you through the steps.

The first change is how you’ll define the PRIMARY KEY on the table with the CREATE TABLE statement.  Instead of adding PRIMARY KEY CLUSTERED on the column definition, add it to the table as a constraint.

CREATE TABLE dbo.NonRandomPKandDC
(
NonRandomPKandDCID int IDENTITY(1,1)
,Column1 datetime
,CONSTRAINT PK_NonRandomPKandDC_RandomPKandDCID PRIMARY KEY CLUSTERED (NonRandomPKandDCID)
)

Next you want to use the ALTER TABLE statement to add the DEFAULT CONSTRAINT.  Instead of making the default part of the column definition in the CREATE TABLE, you want to name the default as a constraint to name it as it is created.

ALTER TABLE dbo.NonRandomPKandDC ADD CONSTRAINT DF_NonRandomPKandDC_Column1
DEFAULT (getdate()) FOR [Column1]

Take a look at the results of the next query:

SELECT name FROM sys.objects
WHERE parent_object_id = OBJECT_ID('dbo.NonRandomPKandDC')

image

On your server and mine the objects will have the same name.  When you deploy objects build from T-SQL like this from development to test to production they will have the same names.

What the!?

Now there isn’t anything wrong with these random names from the perspective of how your database will perform.  But it will hose up things such as database comparisons and investigating errors.

With database comparisons, the issue is pretty obvious.  If the contents of the object are the same but the name is different then it isn’t the exact same object.  Many tools have options for ignoring these names, but there are some that don’t.  Even when the tool has the option to ignore, you will need to rely on the operator of the tool to disable the feature.

Looking now at investigating errors, I am a big fan of errors that can tell me the problem within the database.  Which of the following is easier to understand.  The first with the random name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK__RandomPKandDC__5D60DB10′. Cannot insert duplicate key in object ‘dbo.RandomPKandDC’.
The statement has been terminated.

Or the second with the stated name:

Msg 2627, Level 14, State 1, Line 2
Violation of PRIMARY KEY constraint ‘PK_NonRandomPKandDC_RandomPKandDCID’. Cannot insert duplicate key in object ‘dbo.NonRandomPKandDC’.
The statement has been terminated.

Ok, maybe this isn’t the best example of this type of issue, but it does tell me exactly the issue and because I named the object explicitly I know where the problem is and something about the issue before digging into the schema of the table.

Overall, this is about reducing pain points in building and using your databases.  The easier it is to manage them once they are deployed, the more Bejeweled Blitz you can play on Facebook between your projects.

Renaming the Objects

Maybe I’ve sold you on this idea.  If so, you may be thinking “What the heck do you do with all of my existing databases objects?”  That answer is simple… rename them.  Since the names of these objects isn’t tied to how they are defined, you can easily get them renamed with sp_rename.

The following two scripts are what I use to rename PRIMARY KEY CONSTRAINTS and DEFAULT CONSTRAINTS.

This first one will provide sp_rename statements that you can execute to rename all of your PRIMARY KEY CONSTRAINTS:

;WITH PKNames
AS (
SELECT name AS IndexName
,OBJECT_NAME(object_id) AS TableName
,OBJECT_SCHEMA_NAME(object_id) as SchemaName
,(SELECT '' + c.name
FROM sys.index_columns ic
INNER JOIN sys.columns c
ON ic.object_id = c.object_id
AND ic.index_column_id = c.column_id
WHERE ic.object_id = i.object_id
AND ic.index_id = i.index_id
AND ic.is_included_column = 0
ORDER BY ic.key_ordinal
FOR XML PATH('')) AS Columns
FROM sys.indexes i
WHERE i.is_primary_key = 1
)
SELECT 'EXEC sp_rename ''' + QUOTENAME(SchemaName) + '.' + QUOTENAME(IndexName) + ''', ''PK_' + TableName + '_' + Columns + ''''
FROM PKNames
WHERE IndexName <> 'PK_' + TableName + '_' + Columns

The second one will provide sp_rename statements that you can execute to rename all of your DEFAULT CONSTRAINTS:

SELECT 'EXEC sp_rename ''' + QUOTENAME(OBJECT_SCHEMA_NAME(dc.parent_object_id)) + '.'
+ QUOTENAME(dc.name) + ''', ''DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name + ''''
FROM sys.default_constraints dc
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND dc.parent_column_id = c.column_id
WHERE dc.name <> 'DF_' + OBJECT_NAME(dc.parent_object_id) + '_' + c.name

Hopefully these can be helpful for you as well.

Conclusion

In a roundabout way, this post has been about naming conventions.  Make the world a prettier place by having a convention on naming the objects in your database.

Last word… don’t just run out and use this in your production database without doing your own testing and promoting using your own company’s deployment process.  An obvious statement but one that I thought I should point out since I know how tempting this can be.

EDIT 2010/05/27: Modified scripts to account for schema variations.

The Power of N

A peer the other day was having some trouble storing some some Chinese characters in a database.  Every time he would insert the data into his table, the results would look similar to the following.

image

The phrase he was adding was similar to the following:

烟肉独角兽彩虹乳酪

The T-SQL he was using was forwarded to me and it looked like the following:

USE tempdb
GO

CREATE TABLE #AnotherLanguage
(Chinese nvarchar(50))
GO

INSERT INTO #AnotherLanguage
VALUES('烟肉独角兽彩虹乳酪')
GO

SELECT * FROM #AnotherLanguage

The title may have given a hint as to the issue he was facing.  To pass the string into the table as nvarchar it needs to be prefaced with the letter N.  One character with so much power.

See below…

USE tempdb
GO

CREATE TABLE #AnotherLanguage
(Chinese nvarchar(50))
GO

INSERT INTO #AnotherLanguage
VALUES(N'烟肉独角兽彩虹乳酪')
GO

SELECT * FROM #AnotherLanguage

This time the results are the following…

image

Not exactly an exciting issue, but a helpful one to recall none the less.  There was one other thing that needed to be done, that was a quick update to the installed languages.  This, though, didn’t seem to be an issue on my Windows 7 machine.

image001

Hope this helps someone else.

ABCs of CTEs at PASSMN

IBM ABC DinoLast week I presented at the March Minnesota SQL Server User Group (PASSMN) meeting on using CTEs in SQL Server.  The session is meant as an overview and introduction to CTEs with some examples of their use and what some of the effects can be.

Overall the session was well received and I got the following scores:

Area Rating (1-5)
Effectiveness of Demos 4.211
Usefulness of Materials 4.289
Presenter Skills 4.211
Blend of Demos 4.447
Overall presentation 4.289

I had some pretty good comments from the attendees:

  • Demos can be better organized
  • Good job
  • Great display of CTE uses
  • Great stuff – I can’t wait to start putting them to use
  • I found it to be a very interesting demonstration. My work still uses SQL 2000, but they’re looking to conver to 2008 later this year, so good.
  • Very informative

And some that a little less than happy but still very useful for the next time I do this presentation:

  • Seemed like too much time was spent on the surface repeating examples when we could have gone further in depth.
  • Add some useful examples for takeaway
  • Too much focus on simple example and not enough focus on complex useful examples
  • Lots to cover, a bit rushed due to time constraints

For those that want to dig into some of the examples provided, here is the presentation for download.

SSWUG Spring ‘10 Ultimate Virtual Conference

13_02_42

The SSWUG Spring 2010 Virtual Conference is coming up.  On April 7, 8, and 9, attend a conference from the comforts of your living room, office, or couch.  And while you are at it you’ll get to sit on on some incredible presentations, interaction with speakers, chat with other attendees, make new contacts, lots of fun and surprises.

  • More than 80 technical sessions
  • These are NOT sales presentations.
  • Live keynote presentations and interaction
  • On-Demand access to sessions for 45 days – miss a session? No problem.
  • Chat, Twitter Integration, SKYPE integration for Q&A
  • Experience-based learning – find out what you need to know from people that are using the technology every day
  • 6-Month SSWUG.ORG Membership (or membership extension), included!
  • ALL-ACCESS Pass: SQL Server and Business Intelligence… SharePoint and .NET technologies – all included, one low price
  • Great vendor hall – learn about the best tools, technologies, publications and partners out there for your shop
  • Learning, learning and more learning

If this sounds as awesome as it is, register for the event here.  Among the presenters will be myself with the following topics:

Using XML to Query Execution Plans

SQL Server stores its execution plans as XML in dynamic management views. The execution plans are a gold mine of information. From the whether or not the execution plan will rely on parallelism to what columns are requiring a key lookup after a non-clustered index seek. Through a the use of XML this information can be available at your finger tips to help determine the value and impact of an index and guide you in improving the performance of your SQL Server databases.

Prerequisites

  • Understanding of basic T-SQL coding
  • Understanding of basic XQuery statements

Goals:

  1. Discuss information available in an execution plan
  2. Demonstrate use of XQuery to query execution cache
  3. Demonstrate methods to performance tune

Getting To Know Your Indexes

Without proper indexing SQL Server can be hard pressed to create efficient and performant execution plans. Dynamic Management Views (DMV) and system views provide a slew of information about indexes that can be used to analyze indexes within SQL Server. In this session we’ll go under the hood of SQL Server to look at DMVs and system views to know what indexes you have, should have, and how they feel about the way applications are treating them.

Prerequisites

  • Understanding of performance tuning needs
  • Experience with Database design

Goals:

  1. Identify methods to analyze current and potential indexes
  2. Learn how to alleviate stress found on indexes
  3. Demonstrate methods for tuning indexes

A Function By Any Other Name Is A Function, Right? Right?!?

User defined functions provide a means to encapsulate business logic in the database tier. Often the purpose of the encapsulation is to provide standard method access segments of data within the database. Unfortunately, not all methods of creating user defined functions are equal. In this session we’ll review the types of user defined functions and investigate the performance impact in selecting the different types

Prerequisites

  • Understanding of basic T-SQL

Goals:

  1. Identify purposes for creating user defined functions
  2. Discuss the types of user-defined functions
  3. Demonstrate performance impact in selecting different types of functions

Stop in an check it out, there will be a lot of great sessions and great conversation.

March PASSMN Meeting Tonight (03/16/2010)

I am Here for the Learning Revolution

It’s come down to a decision… do you want to learn about SQL Server and network with your peers or don’t you.  Then again, the question could also be do you want some swag and pizza with some work buddies.  Hopefully, you’ll be stopping in for the first item.

Out meeting is today starting at 2:30 PM for networking with announcements an presentations beginning at 3:00 PM.

This month we have Louis Davidson joining us for:

Database Design Fundamentals

In this session I will give an overview of how to design a database, including the common normal forms and why they should matter to you if you are creating or modifying SQL Server databases. Data should be easy to work with in SQL Server if the database has been organized as close as possible to the standards of normalization that have proven for many years. Many common T-SQL programming “difficulties” are the result of struggling against the way data should be structured and can be avoided by applying the basic normalization techniques and are obvious things that you find yourself struggling with time and again (i.e. using the SUBSTRING function in a WHERE clause meaning you can’t use an index efficiently).

And before that, I’ll be presenting:

ABCs of CTEs

Common Table Expressions (CTE) aren’t as common as their name implies. CTEs are often seen as a secret part of the dark art of recursion. This session will explore CTEs to show how they can be extremely useful in improving performance and legibility of T-SQL code. And, of course, we will look at their use in returning recursive data.

Hope to see you there.  If you have any questions, you can reach me on twitter.