0

I am trying to write a function which processes a column value and returns the value with everything before the '@' symbol.

I have managed to do this so far by using the following code:

Create Function fnStaffCodeConvert (@staffcode varchar(10))
Returns varchar(4)
AS
BEGIN
    DECLARE     @staffinitals varchar(4)
    SET @staffinitals = (SELECT substring(@staffcode,0, CHARINDEX('@',@staffcode)))
    Return @staffinitials
END

Example result from function - Parameter in = ABC@123, Returns = ABC.

This works but then exclusively returns every result where the column contained an @ value and the remaining results without the @ are omitted. I.e. ABC@123 returns ABC but XYZ does not return anything.

How can I amend the code to give me both sets of values? I imagine I would have to put an 'IF' statement in there but I am unsure how to write it to get the results I want.

Many thanks in advance :)

Mike

4

2 回答 2

0

你快到了:

ALTER FUNCTION fnStaffCodeConvert (@staffcode varchar(10))
RETURNS VARCHAR(4)
AS
BEGIN
   DECLARE @staffinitals AS VARCHAR(4)
   if CHARINDEX('@',@staffcode) <> 0    
     SET @staffinitals = (SELECT substring(@staffcode,0, CHARINDEX('@',@staffcode)))
   Else 
   SET @staffinitals = @staffcode   

   RETURN @staffinitals
END
于 2013-07-31T15:41:25.780 回答
0

你可以用 a 做你想做的事case

Create Function fnStaffCodeConvert (@staffcode varchar(10))
Returns varchar(4);
AS
BEGIN
    DECLARE     @staffinitals varchar(4);
    SET @staffinitals = (SELECT (case when @staffcode like '%@%'
                                      then substring(@staffcode,0, CHARINDEX('@',@staffcode)
                                      else @staffcode
                                  end));
    Return @staffinitials;
END

但是等等,您可以进一步简化:

Create Function fnStaffCodeConvert (@staffcode varchar(10))
Returns varchar(4)
AS
BEGIN
    DECLARE @staffinitals varchar(4)
    SELECT @staffinitials = (case when @staffcode like '%@%'
                                  then substring(@staffcode,0, CHARINDEX('@',@staffcode)
                                  else @staffcode
                             end);
    Return @staffinitials;
END;
于 2013-07-31T15:41:51.137 回答