Recently trying to debug some really cryptic T-SQL scripts.

Guess what this is trying to do?

--
DECLARE @dt varchar(6)
SET @dt = RIGHT(CONVERT(varchar(4), YEAR(getdate())),2) + REPLICATE('0', 2 - LEN(CONVERT(varchar(2), MONTH(getdate())))) + CONVERT(varchar(2), MONTH(getdate())) + REPLICATE('0', 2 - LEN(CONVERT(varchar(2), DAY(getdate())))) + CONVERT(varchar(2), DAY(getdate()))
--

Answer:

It’s trying to print the current date in YYMMDD format.

Uhm, there’s a much better way to do this.

Try CONVERT.

--
SET @dt =  CONVERT(VARCHAR(6), GETDATE(), 12)
--

I still quite enjoy debugging or refactoring T-SQL scripts, but sometimes I’m just amazed at what I still see …

VN:F [1.9.22_1171]
Rating: 9.9/10 (12 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Refactor This: Runaway T-SQL to Print YYMMDD, 9.9 out of 10 based on 12 ratings  
Be Sociable, Share!
  • Tweet