You might consider using DATEDIFF
with the TIME
portion only and leverage the formatting options within CONVERT
to make a simpler output. Since this might be used all over in reporting as you suggested, perhaps wrap it into a scalar function as well (then use that in report queries or even as calculated fields).
CREATE FUNCTION dbo.f_GetDateValue(
@Date DATETIME,
@Digits INT = 4 -- How many digits of precision?
) RETURNS VARCHAR(50) AS
BEGIN
-- Calculate decimal to millisecond level
DECLARE @Decimal NUMERIC(9,0) = ROUND(CONVERT(NUMERIC(9,0),
DATEDIFF(MS, 0, CONVERT(TIME, @Date)))/86400000, @Digits)
-- Return formatted date and time as decimal
RETURN CONVERT(CHAR(10), @Date, 121) -- Format date as yyyy-MM-dd
+ ' ' -- Separate date and time value
+ LEFT(CONVERT(VARCHAR(50), @Decimal), @Digits + 2) -- 2 for "0." and rounded @Digits
END
GO
With scalar function above, your query is then just:
SELECT dbo.f_GetDateValue(GETDATE(), DEFAULT) -- Gets "yyyy-MM-dd 0.0000"
SELECT dbo.f_GetDateValue(GETDATE(), 2) -- Gets "yyyy-MM-dd 0.00"
As noted in comments and other answers, you cannot change how SQL is storing date values. This creates a text-based representation only that is only as sortable as the format of the text. Fortunately, since you are using YYYY-MM-DD 0.0000
, this should be sortable in most reports as the text itself.