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 …
No related posts.
Filed under:
musings











I would prefer
SET @dt = RIGHT(CONVERT(varchar(4), YEAR(getdate())),2)
+ RIGHT(’0′ +CONVERT(varchar(2), MONTH(getdate())),2)
+ RIGHT(’0′ +CONVERT(varchar(2), DAY(getdate())),2)
Wow, that example was so ugly.
Although I think it’s time for a converter from date to a custom date string as in this connect issue:
https://connect.microsoft.com/SQLServer/feedback/details/530045
1.) Dev doesn’t know(or read) BOL is the ultimate reference
2.) He/she was a xbase developer
Mother of gawd that is terrible. CONVERT is the way to go.