Friday, October 26, 2007

Do you want to laugh or cry?

I don't know if I should laugh or cry after looking at this code. This could not have been written by a human right?

Anyway here it is, consider it a teaser. If you want to torture yourself and look at the whole query then go here:

HAVING (((1 = 1)
AND (PP.Created >= ISNULL(NULL,'1/1/1900')
AND PP.Created < 1 =" 2)">= ISNULL(NULL,'1/1/1900')
AND (MIN(PV.Visit)) < DATEADD(d, 1, ISNULL(NULL,'1/1/3000')))

AND pv.DoctorId IN (NULL))

WHEN '0' = 1 THEN df.ListName
WHEN '0' = 2 THEN df2.ListName
WHEN '0' = 3 THEN ic.ListName

Someone will red flag the post, here is the whole query.

/* New Patient Analysis */


[PatientProfileId] [int] NOT NULL ,
[Prefix] [varchar] (10) NULL ,
[First] [varchar] (30) NULL ,
[Middle] [varchar] (30) NULL ,
[Last] [varchar] (30) NULL ,
[Suffix] [varchar] (20) NULL ,
[Created] [datetime] NOT NULL

Insert #PatientTemp

SELECT PP.PatientProfileId, PP.Prefix, PP.First, PP.Middle, PP.Last, PP.Suffix,
WHEN 1 = 1 THEN PP.Created
WHEN 1 = 2 THEN Min(PV.Visit)
END As Created

FROM PatientVisit PV
INNER JOIN PatientProfile PP ON PP.PatientProfileId = PV.PatientProfileId

GROUP BY PP.PatientProfileId, PP.Prefix, PP.First, PP.Middle, PP.Last, PP.Suffix, PP.Created

HAVING (((1 = 1)AND
(PP.Created >= ISNULL(NULL,'1/1/1900') AND PP.Created < DATEADD(d, 1, ISNULL(NULL,'1/1/3000')))
((1 = 2)AND
((MIN(PV.Visit) >= ISNULL(NULL,'1/1/1900') AND (MIN(PV.Visit)) < DATEADD(d, 1, ISNULL(NULL,'1/1/3000')))

Order By PP.First, PP.Last

SELECT dbo.FormatName(#PatientTemp.Prefix, #PatientTemp.First, #PatientTemp.Middle, #PatientTemp.Last, #PatientTemp.Suffix) AS Name,
WHEN 1 = 1 THEN #PatientTemp.Created
WHEN 1 = 2 THEN Min(pv.Visit)
END As Created,
COUNT(*) AS [Number Of Visits],
SUM(pva.OrigInsAllocation + pva.OrigPatAllocation) AS Charges,
SUM(pva.InsPayment + pva.PatPayment) AS Payments,
WHEN '0' = 1 THEN df.ListName
WHEN '0' = 2 THEN df2.ListName
WHEN '0' = 3 THEN ic.ListName
END As Grouping

FROM PatientVisit pv
INNER JOIN PatientVisitAgg pva ON pv.PatientVisitId = pva.PatientVisitId
INNER JOIN #PatientTemp ON pv.PatientProfileId = #PatientTemp.PatientProfileId
INNER JOIN DoctorFacility df ON pv.DoctorId = df.DoctorFacilityId
LEFT JOIN DoctorFacility df1 ON pv.ReferringDoctorId = df1.DoctorFacilityId
LEFT JOIN DoctorFacility df2 ON pv.FacilityId = df2.DoctorFacilityId
LEFT JOIN InsuranceCarriers ic ON ic.InsuranceCarriersId = pv.PrimaryInsuranceCarriersId

(NULL IS NOT NULL AND pv.ReferringDoctorId IN (NULL)) OR
AND --Filter on insurance carrier
(NULL IS NOT NULL AND ic.InsuranceCarriersId IN (NULL)) OR

GROUP BY #PatientTemp.Created,dbo.FormatName(#PatientTemp.Prefix, #PatientTemp .First, #PatientTemp.Middle, #PatientTemp.Last, #PatientTemp.Suffix),
WHEN '0' = 1 THEN df.ListName
WHEN '0' = 2 THEN df2.ListName
WHEN '0' = 3 THEN ic.ListName

HAVING (((1 = 1)AND
(#PatientTemp.Created >= ISNULL(NULL,'1/1/1900') AND #PatientTemp.Created < DATEADD(d, 1, ISNULL(NULL,'1/1/3000')))
((1 = 2)AND
((MIN(pv.Visit) >= ISNULL(NULL,'1/1/1900') AND (MIN(pv.Visit)) < DATEADD(d, 1, ISNULL(NULL,'1/1/3000')))

ORDER BY dbo.FormatName(#PatientTemp.Prefix, #PatientTemp.First, #PatientTemp.Middle, #PatientTemp.Last, #PatientTemp .Suffix), #PatientTemp.Created
Drop table #PatientTemp

Friday, October 19, 2007

Sort Values Ascending But NULLS Last

This is a frequent request in newsgroups and fora. People want to sort the column in ascending order but don't want the NULLS at the beginning.
Oracle has this syntax: ORDER BY ColumnName NULLS LAST;
SQL Server does not have this. But there are 2 ways to do this. The first one is by using case and the second one by using COALESCE and the maximum value for the data type in the order by clause.

The 2 approaches with a datetime data type

DECLARE @Temp table(Col datetime)
INSERT INTO @Temp VALUES(getdate())
INSERT INTO @Temp VALUES('2007-10-19 09:54:03.730')
INSERT INTO @Temp VALUES('2006-10-19 09:54:03.730')
INSERT INTO @Temp VALUES('2005-10-19 09:54:03.730')
INSERT INTO @Temp VALUES('2006-10-19 09:54:03.730')
INSERT INTO @Temp VALUES('2004-10-19 09:54:03.730')

FROM @Temp
ORDER BY COALESCE(Col,'9999-12-31 23:59:59.997')

FROM @Temp
ORDER BY CASE WHEN Col Is NULL Then 1 Else 0 End, Col

The 2 approaches with an integer data type

DECLARE @Temp table(Col int)

FROM @Temp
ORDER BY COALESCE(Col,'2147483647')

FROM @Temp
ORDER BY CASE WHEN Col Is NULL Then 1 Else 0 End, Col

Monday, October 15, 2007

Interview With Kalen Delaney About Inside Microsoft SQL Server 2005 Query Tuning and Optimization

Inside Microsoft SQL Server 2005: Query Tuning and Optimization I am a big fan of Inside Microsoft SQL Server 2005 The Storage Engine so when I saw that yet another book got published in this series I just had to check it out. Inside Microsoft SQL Server 2005: Query Tuning and Optimization is very well written gets to the point and give you the answers that you need. I decided to contact Kalen to see if she would be willing to do an interview, by now you know that the answer is yes of course ;-)

The question-and-answer session with Kalen that follows was conducted via email.

What is the audience for this book, is it the enterprise user or can a small department benefit from the tips in this book?
Because this book deals with query tuning, anyone who writes SQL queries for SQL Server can benefit. Very little in the book is geared towards system tuning, so the size of the machine doesn’t really matter. Now of course, if you have a very small system with very small tables, you won’t get as much benefit out of tuning your queries. However, if you have any tables of more than a few thousand rows, and you do any joins, you will need to tune your queries. In addition, the issues of blocking and concurrency control can impact any system, no matter how small.

What new technologies in SQL Server 2005 do you think are the most beneficial for performance?
For very large databases, the best new technology is partitioning. For any size system, if you have had serious performance problems due to blocking, you might find a big performance benefit by using one of the snapshot-based isolation levels, but you really need to understand the resource costs that come along with the improved performance. For your individual queries, I think the new optimizer hints and query level recompiles can make a big difference. For indexes, the ability to add included columns to nonclustered indexes can give some of your hard-to-tune queries a major performance boost.

What will a person who reads this book gain in terms of understanding how to performance tune a server?
The focus of this book is not so much on tuning the server, but on tuning queries. There is more in Inside SQL Server 2005: The Storage Engine on server issues such as memory and processor management. The biggest server wide issues are covered in Chapter 5, when I talk about managing the plan cache, and how and when query plans are reused.

Is the book geared towards a beginner/intermediate level user or do you have to be an advanced user to really utilize the information in this book?
The book is not geared towards beginners, but everyone should be able to get something out of it. It’s primarily geared to SQL Server developers and DBA’s who have been working with SQL Server for a while, and have encountered performance problems that they are trying to find solutions for.

With all the changes in SQL Server 2005, how critical has the tempdb become in regards to performance?
Tempdb has always been important. In SQL Server 2005, if you are using one of the snapshot-based isolation levels, you are going to have to be more aware of the demands placed on tempdb, both in the sizing requirements and the additional I/O resources needed. Fortunately, SQL Server 2005 provides tools to monitor tempdb, including a dozen new performance monitor counters, and a dynamic management view, sys.dm_db_file_space_usage, that keeps track of how much space in tempdb is being used for each of the different kind of object stored in tempdb.

I understand that this is the first time you wrote with a team of other writers; can you tell us something about that experience?
I initially thought that not having to write the whole volume by myself meant that I could get it done sooner, but that was not the case. Everyone had their own schedule and their own way of writing. The personal aspect of working with the other authors was great. I deeply respect all of the others and it was an honor to be working so closely with them. I had some concerns about the depth of coverage and I wondered whether all the chapters would end up being as deep as I hoped for, but that turned out not to be a major problem. The only real issues were agreeing on a common terminology and coding style, and even that wasn’t that big of an issue, because I got to do a final editing pass on everyone’s chapters.

What SQL Server books are on your bookshelf?
All of the Inside SQL Server books are there, of course, and all of Ken Henderson’s books. Bob Beauchemin’s book is in my car, to read while I am waiting for the ferryboat, and while on the ferry. I also have technical books that aren’t SQL Server specific, such as Jim Gray’s Transaction Processing, Russinovich’s and Solomon’s Windows Internals, Chris Date’s Introduction to Database Systems and Mike Stonebraker’s Readings in Database Systems.

Why do you write technical books?
I love working with SQL Server and trying to find out all I can about it. When I found that I could explain difficult concepts in a training environment, I thought I could do the same thing in a written format, and reach more people that way. I have always loved explaining things, ever since I was a teaching assistant for High School Math.

Will you be updating your books for SQL Server 2008?
I have just started meeting with my editors at Microsoft Press about SQL Server 2008, and it looks like a revision is in the plans. We’re really looking at it as just a revision, with the same structures as the current books, with straightforward changes and the inclusion of new features.

Name three things that are new in SQL Server 2005 that you find are the most valuable?
Dynamic Management Views, Dynamic Management Views, and Dynamic Management Views!
Oh, you wanted three different things? ;-) How about XML query plans and optimization hints. (I’m also very fond of many of the new TSQL constructs, but I was only talking about things that I cover in my new book.)

Name three things which are coming in SQL Server 2008 that you are most excited about?
You’ll have to ask me this next time. I have actually been avoiding SQL Server 2008 while I was getting my Query Tuning and Optimization book finished, because I didn’t want to get distracted.

Can you list any third party tools that you find useful to have as a SQL Server developer/admin?
I’ve tried a few other products, but usefully I find that it is much easier to just stick with the Microsoft line and use the tools provided with the product.

Name some of your favorite non-technical books.
Oh, I love to read. It would be impossible to list my favorite books, but I can tell you my favorite authors, most of whom write science fiction: Lois McMaster Bujold, Ursula LeGuin, Sheri Tepper, Orson Scott Card, Octavia Butler, Elizabeth Moon. I also love to read historical fiction like Leon Uris.

Wednesday, October 10, 2007

SQL Teaser: Guess the output

What do you think will be the output?

DECLARE @d datetime
SET @d = '20071010'

SELECT DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1)

After that run this to see how to get first and last days for years, quarters, months and weeks(be careful of ISO weeks!)

DECLARE @d datetime
SET @d = '20071010'

SELECT DATEADD(yy, DATEDIFF(yy, 0, @d), 0) as FirstDayOfYear,
DATEADD(yy, DATEDIFF(yy, 0, @d)+1, -1) as LastDayOfYear,
DATEADD(qq, DATEDIFF(qq, 0, @d), 0) as FirstDayOfQuarter,
DATEADD(qq, DATEDIFF(qq, 0, @d)+1, -1) as LastDayOfQuarter,
DATEADD(mm, DATEDIFF(mm, 0, @d), 0) as FirstDayOfMonth,
DATEADD(mm, DATEDIFF(mm, 0, @d)+1, -1) as LastDayOfMonth,
DATEADD(wk, DATEDIFF(wk, 0, @d), 0) as FirstDayOfWeek,
DATEADD(wk, DATEDIFF(wk, 0, @d)+1, -1) as LastDayOfWeek

Tuesday, October 09, 2007

Self-paced Course: What's New in Microsoft SQL Server 2008

In this clinic, you will learn about the new and enhanced features included in SQL Server 2008. You will explore the new data types and the data management features. Additionally, you will learn about the enhanced Integration Services, Analysis Services, and Reporting Services included in SQL Server 2008. This online clinic is composed of a rich multimedia experience.

To get the most out of this clinic, it is recommended that you have:

  • Knowledge of general SQL database concepts that are largely independent of a specific version of SQL Server
  • Knowledge of Microsoft SQL Server 2005 features
  • Knowledge of deploying and upgrading database solutions
  • Knowledge of how to solve performance issues related to SQL Server hardware
  • Performed the job role of a SQL Server 2005 database administrator or database developer
  • Product or technology experience in Microsoft SQL Server 2000 or SQL Server 2005

At the end of the course, students will be able to:

  • Describe the features of SQL Server 2008 and their benefits.
  • Describe the features of enterprise data platform that help you to secure data in applications.
  • Describe the dynamic development features that facilitate the development of database applications.
  • Describe the features of SQL Server 2008 that provide data storage solutions beyond relational databases.
  • Describe the enhanced features in SSIS that help you to integrate data effectively.
  • Describe the enhanced features in SSAS that help you to improve the BI infrastructure.
  • Describe the enhanced features in SSRS that help you to improve the scalability of the reporting engine.

Modules & Lessons

Clinic Overview

Module Introduction
Navigation Overview
Clinic Information

What’s New in SQL Server 2008
Module Introduction

Overview of SQL Server 2008
Lesson Introduction
Enhancements in SQL Server 2008
New Features of SQL Server 2008
Self Test

Enterprise Data Platform
Lesson Introduction
Methods for Data Encryption
Security Auditing for Data Protection
Resource Management Features
Benefits of the Resource Governor Tool
System Analysis Features
Server Management Features
Self Test

Dynamic Development
Lesson Introduction
Data Entities in SQL Server 2008
Data Synchronizing Features
Self Test

Beyond Relational Databases
Lesson Introduction
New Data Types
Spatial Data Type
Table-Value Parameters in SQL Server 2008
Features of Integrated Full-Text Search in SQL Server 2008
Self Test

Pervasive Insight in Integration Services
Lesson Introduction
Data Integration Features
The MERGE Statement in SQL Server 2008
Self Test

Pervasive Insight in Analysis Services
Lesson Introduction
Enhanced Features in Analysis Services
How the Block Computation Feature Works
Self Test

Pervasive Insight in Reporting Services
Lesson Introduction
How Reporting Services Work
Features for Microsoft Office 2007 Integration
The Report Authoring Tool
Report Builder Enhancements
What Is Tablix?
Self Test
Module Summary

Module Introduction

Start here:

    Wednesday, October 03, 2007

    LAMP + Porn = perfect Job?

    Found this here:

    Senior Software Engineer – Linux/Apache/Mysql/Perl

    We are a small, San Francisco-based company seeking a lead software engineer/architect to take over development of our subscription-based adult video web site. You will work with our fabulously talented product manager, marketer, and engineering support to improve our service and take it to new levels of traffic and success.

    You must be extremely skilled in the following technologies, so that you can both keep the current site running and extend it:

    Linux (packaging systems, network configuration, debugging, tweaking)
    Perl (in the form of command line scripts, cgi scripts, and complete libraries)
    Apache (building and tweaking the 1.3 variants, and the mod_perl module)
    MySQL (SQL and performance tuning)
    Java (from servlets to applications; including Hibernate, Spring, Log4j and other open source java libraries/frameworks)

    Additionally, you must be very familiar with the following technologies that you will encounter, or the ability to quickly come up to speed on them:


    You possess the skill-sets of both a system administrator and programmer. You can set up and configure a server to make it do what you want; you can discover, configure and compile applications to make them do what you want; and you can write the code to customize and tie all these things together. There is no part of a system that you are afraid to venture into, nor do you find application writing boring or too complex.

    You are a developer who can do anything that you put your mind too; and you live and breathe open source software. You are goals focused, and take great pride in completing and optimizing working applications. You can communicate with business people to find out what needs to be done and how it should be prioritized, and you have the confidence and skill to make it happen. You know the latest tools and technologies that are available that might replace what we’ve got. You actively seek this information and are always looking for better ways to do things.

    Finally, you have no problem serving up gigabytes and gigabytes of pornography. In fact, you find the challenge of pushing out a sustained 3Gb/s of pornography to be an extremely interesting engineering problem.

    Required skills: Perl/mod_perl

    Tuesday, October 02, 2007

    How to find out the recovery model for all databases on SQL Server 2000, 2005 and 2008

    How do you find out the recovery model for all the databases on your SQL Server box?
    On a SQL Server 2005/2008 box you can use the sys.databases view, the sys.databases view returns a column named recovery_model_desc.
    On a SQL server 2000 box you will have to use the DATABASEPROPERTYEX function. The 2000 version will also work on 2000 and 2008 (I tested this with the July CTP)

    --2005/2008 version
    SELECT [name],
    FROM sys.databases

    --2000/2005/2008 version
    SELECT [name],
    DATABASEPROPERTYEX([name],'Recovery') AS recovery_model_desc
    FROM master..sysdatabases

    Monday, October 01, 2007

    SQL Teaser: Guess the output

    Here is a small teaser, can you guess the output?

    SELECT d.c-d.b/d.a
    FROM(SELECT 1,2,5)d(a,b,c)