Jeff Smith Blog

Random Thoughts & Cartesian Products with Microsoft SQL Server

SQL Server 2005: Using PARTITION and RANK in your criteria

The RANK and PARTITION features in 2005 are simply amazing. They make so many "classic" SQL problems very easy to solve. For example, consider the following table: create table Batting(Player varchar(10), Year int, Team varchar(10), HomeRuns int, primary key(Player,Year))insert into Battingselect 'A',2001,'Red Sox',13 union allselect 'A',2002,'Red Sox',23 union allselect 'A',2003,'Red Sox',19 union allselect 'A',2004,'Red Sox',14 union allselect 'A',2005,'Red Sox',11 union allselect 'B',2001,'Yankees',42 union allselect 'B',2002,'Yankees',39 union allselect 'B',2003,'Yankees',42 union allselect 'B',2004,'Yankees',29 union allselect 'C',2002,'Yankees',2 union allselect 'C',2003,'Yankees',3 union allselect 'C',2004,'Red Sox',6 union allselect 'C',2005,'Red Sox',9 Suppose we would like to find out which year each player hit their most home runs, and which team they played for. Read more →

Simple T-SQL Proper Case User-Defined Function

I posted this one a long time ago and needed to use it today, so I thought I'd post it up here as well in case anyone finds it useful. This simply attempts to capitalize the first letter of each word for the string passed in. Read more →

Vulnerable to SQL Injection?

One of the things that troubles me most about SQL Injection is that is seems it is still very misunderstood. Is the following psuedo-code vulnerable to SQL Injection? String SearchTerm = {some user input here, unvalidated and unscrubbed -- uh oh ! Read more →

Another SQL Suduko Solver

There's been quite a few posts out there with SQL implementations of Suduko puzzle solvers: This one is a T-SQL solver, but it really doesn't do any set-based operations and doesn't really make use of SQL that much. Read more →

SQL GROUP BY techniques

One aspect of the versatile SELECT statement that seems to confuse many people is the GROUP BY clause. It is very important to group your rows in the proper place. Always push GROUP BY aggregations as far into your nested SELECT statements as possible – if you have a situation in which you are grouping by long lists of columns that are not part of primary keys, you are probably have not structured your query correctly. Read more →