I am having an issue getting a case statement to work withing a custom function that I am writing to add dashes to a SSN within my application. I have written the function as such:
But when I go to execute the script and create the function, I get errors on the case statement that I cannot figure out:
The only thing that I can think of is that you cannot use a case statement outside of a select statement, but that would seem odd to me since you can use an If...Then construct outside of a select statement. I haven't tried writing the function using If...Then yet, as I would rather use the case statement, but I suppose if I have to I will. Am I right in thinking that I can't use the case statement? If not, what have I done wrong? Thanks in advance for any help!
Code:
USE HRDev
GO
CREATE FUNCTION dbo.fn_FixSSN (@SSN as char(11))
RETURNS char(11)
AS
BEGIN
CASE LEN(@SSN)
WHEN 7 THEN SET @SSN = ('00' + Left(@SSN,1) + '-' + Substring(@SSN,2,2) + '-' +
Right(@SSN,4))
WHEN 8 THEN SET @SSN = ('0' + Left(@SSN,2) + '-' + Substring(@SSN,3,2) + '-' +
Right(@SSN,4))
ELSE SET @SSN = (Left(@SSN,3) + '-' + Substring(@SSN,4,2) + '-' +
Right(@SSN,4))
END
RETURN @SSN
END
But when I go to execute the script and create the function, I get errors on the case statement that I cannot figure out:
Code:
[COLOR=red]
Msg 156, Level 15, State 1, Procedure fn_FixSSN, Line 6
Incorrect syntax near the keyword 'CASE'.
Msg 156, Level 15, State 1, Procedure fn_FixSSN, Line 9
Incorrect syntax near the keyword 'WHEN'.
Msg 156, Level 15, State 1, Procedure fn_FixSSN, Line 11
Incorrect syntax near the keyword 'ELSE'.
Msg 156, Level 15, State 1, Procedure fn_FixSSN, Line 14
Incorrect syntax near the keyword 'RETURN'.
Msg 102, Level 15, State 1, Procedure fn_FixSSN, Line 15
Incorrect syntax near 'END'.
[/color]
The only thing that I can think of is that you cannot use a case statement outside of a select statement, but that would seem odd to me since you can use an If...Then construct outside of a select statement. I haven't tried writing the function using If...Then yet, as I would rather use the case statement, but I suppose if I have to I will. Am I right in thinking that I can't use the case statement? If not, what have I done wrong? Thanks in advance for any help!