SELECT dbo.LongitudeFix('23°10''354"')
ALTER FUNCTION LongitudeFix ( @input VARCHAR(80) )
RETURNS FLOAT
AS
BEGIN
IF @input IS NULL
BEGIN
--Just return NULL if input string is NULL
RETURN 0.00
END
--Character variable declarations
DECLARE @output FLOAT
DECLARE @first FLOAT
DECLARE @middle FLOAT
DECLARE @Last FLOAT
--Integer variable declarations
SET @output = 0.00
SET @input = REPLACE(@input, 'S', '')
SET @input = REPLACE(@input, 'E', '')
SET @input = REPLACE(@input, 'N', '')
SET @input = REPLACE(@input, 'W', '')
SET @input = REPLACE(@input, '-', '')
SET @input = REPLACE(@input, ' ', '')
--Variable/Constant initializations
IF ( LEN(@input) > 8 )
BEGIN
SET @first = CAST(LEFT(@input, 2) AS FLOAT)
SET @middle = CAST(SUBSTRING(@input, 4, 2) AS FLOAT) / 60
SET @Last = CAST(REPLACE(SUBSTRING(@input, 7, 4), '"', '') AS FLOAT)
SET @output = @first + @middle + @Last / 3600 * 100000
/ 100000
END
RETURN ROUND(@output,6)
END
GO
I'd love to just have
BEGIN TRY
SELECT @output = CAST(LEFT(@input, 2) AS FLOAT)+
CAST(SUBSTRING(@input, 4, 2) AS FLOAT) / 60+
CAST(REPLACE(SUBSTRING(@input, 7, 4), '"', '') AS FLOAT) / 3600 * 100000 / 100000
END TRY
CATCH TRY
RETURN NULL
END TRY
Much simpler IMO... No check for evvvvvvverrrrrrrrry single possible type of entry. Just does it fit the format, yes/no if yes then churn out answer if no, then nullify... 😎