- Back to Home »
- SQL »
Posted by : Jebastin
Thursday, 19 December 2013
This AddOrdinal function will be useful when we needed to display the date format as 1st July -3rd October. There is nothing in there about ordinals, but it can't be done using String.Format. However it's not really that hard to write a function to do it. The following Microsoft SQL Server Function is used to get the Ordinal Suffix of any number.
- CREATE FUNCTION [Internal].[GetNumberAsOrdinalString]
- (
- @num int
- )
- RETURNS nvarchar(max)
- AS
- BEGIN
- DECLARE @Suffix nvarchar(2);
- DECLARE @Ones int;
- DECLARE @Tens int;
- SET @Ones = @num % 10;
- SET @Tens = FLOOR(@num / 10) % 10;
- IF @Tens = 1
- BEGIN
- SET @Suffix = 'th';
- END
- ELSE
- BEGIN
- SET @Suffix =
- CASE @Ones
- WHEN 1 THEN 'st'
- WHEN 2 THEN 'nd'
- WHEN 3 THEN 'rd'
- ELSE 'th'
- END
- END
- RETURN CONVERT(nvarchar(max), @num) + @Suffix;
- END