T-SQL Simple Timestamp With Leading Zeros
2008-12-04 by , tagged as
I just had to create a simple string in MS T-SQL that would look like the following:
200812041613
or
yyyymmddhhmm
I solved it this way but I have no idea if this is a good solution (comments welcome):
DECLARE @timestamp AS varchar(12) -- Create Timestamp with leading zeros -- Year SET @timestamp = CONVERT( varchar(4), DATEPART(year, GETDATE() ) ) -- Month IF DATEPART( month, GETDATE() ) < 10 SET @timestamp = @timestamp + '0' + CONVERT( varchar, DATEPART( month, GETDATE() ) ) ELSE SET @timestamp = @timestamp + CONVERT(varchar(2), DATEPART( month, GETDATE() ) ) -- Day IF DATEPART( day, GETDATE() ) < 10 SET @timestamp = @timestamp + '0' + CONVERT(varchar, DATEPART( day, GETDATE() ) ) ELSE SET @timestamp = @timestamp + CONVERT(varchar(2), DATEPART( day, GETDATE() ) ) -- Hour IF DATEPART( hour, GETDATE() ) < 10 SET @timestamp = @timestamp + '0' + CONVERT(varchar, DATEPART( hour, GETDATE() ) ) ELSE SET @timestamp = @timestamp + CONVERT(varchar(2), DATEPART( hour, GETDATE() ) ) -- Minute IF DATEPART( minute, GETDATE() ) < 10 SET @timestamp = @timestamp + '0' + CONVERT(varchar, DATEPART( minute, GETDATE() ) ) ELSE SET @timestamp = @timestamp + CONVERT(varchar(2), DATEPART( minute, GETDATE() ) ) -- Done creating timestamp print N'' + @timestamp
