Why not just use DATEPART
? There's no need to convert the value from a datetime
to a varchar
and then to an int
.
SELECT DATEPART(HOUR, GETDATE());
Edit: on a different note, I strongly suggest you always ensure you declare your length, precision and scale when using a datatype. SELECT CONVERT(varchar, GETDATE(), 108)
will return the whole value here, as (in this case) this it converts the value to a varchar(25)
, however, not declaring these parameters can/does leads to unexpected behaviour.
I've seen many questions where people have asked "Why isn't this working?" because their SP is declared as CREATE PROC MyProc @String varchar AS ...
, or they have a variable declaration of DECLARE @MyVar nvarchar;
, which in both cases means the length has a value of 1; and thus their values are truncated.
Edit for Irony: And no less than an hour later... Substring function not comparing the output; looks like I need to order a new crystal ball. Exactly why not declaring your Length, Precision or Scale is a bad idea.