Wednesday, March 21, 2012

Happy Birthday, SQL Style

There was a birthday in our office recently and it inspired me to send them a SQL statement that "I was getting weird results from" and if they could do me a favor and run it on their system to see what they get. I had them run it against the TWO database (if you are a GP admin, you'll get the subtle joke there when you run it). The one I sent wasn't quite this fancy, but I just couldn't leave it be with that I had so here you are.

Just FYI, it's meant to be obfuscated and a little over-complicated so it's a surprise when run by the birthday guy/girl. It's better if using Windows authentication or a user-specific account (as opposed to 'sa'). I'm sure the trained eye will see through it right away, but for those starting out it's an interesting example of what can be done in SQL.

WITH CTE_HB1 (a,b,c,d) AS
(
    SELECT TOP 1
          MAX(a),MAX(b),MAX(c),MAX(d)
    FROM
          (
          SELECT 
                CHAR(72) + CHAR(65) + CHAR(80) + CHAR(80) + CHAR(89) + CHAR(32) a, 'AA20100' b,CASE DB_NAME() WHEN 'TWO' THEN DB_NAME() ELSE CHAR(84)+CHAR(79) END c,CHAR(89) + 'OU' + CHAR(33) + CHAR(33) d
          UNION ALL
          SELECT 
                'GL20000', CHAR(66) + CHAR(73) + CHAR(82) + CHAR(84) + CHAR(72) + CHAR(68) + CHAR(65) + CHAR(89),CHAR(66) + 'R', 'A' + 'TU'
          ) UPR00100
),
CTE_HB2 (e,f) AS
(
    SELECT CHAR(68) + CHAR(69) + CHAR(65) + CHAR(82),SUSER_SNAME()
)
SELECT a.a  '     1     ', a.b '         2        ', a.c '    3    ', a.d '      4      ' FROM CTE_HB1 a
CROSS APPLY (SELECT 1 a UNION ALL SELECT 2) b
UNION ALL
SELECT a.a,a.b,b.e,b.f FROM CTE_HB1 a
CROSS APPLY CTE_HB2 b
UNION ALL
SELECT a.* FROM CTE_HB1 a