title: Function to split string and reverse it in sql
body: <p>I have a column as "<strong>Name</strong>" in two different tables and i want to split the name into two different columns as "<strong>FirsrName</strong>" and "<strong>LastName</strong>". What I'm doing is to create a function and get the values as First and Last.</p>
  
  <p><strong>Issue:</strong> <br />
  Case 1 - The main issue is in first table, name resides as "Sahil Sharma" so i have to split the name on the basis of space.
  Case 2 - In second table, the name is like "Sharma;Sahil" so I need to split the function on the basis of ; and also reverse it as the output of the function be like: <br/>
  FirstName - Sahil<br />
  LastName - Sharma<br /></p>
  
  <p>I'm a bit begineer in CHARINDEX and SUBSTRINGS, although after reading the MSDN, I have tried this code:
  <code>
  ---Get First Name</p>
  
  <pre><code>    CREATE FUNCTION [dbo].[GetFirstName](@fullname varchar(30))
      RETURNS varchar(20)
      AS 
      BEGIN
  
  DECLARE @name nvarchar(20)
  DECLARE @result [nvarchar](30)
  SET @name = @fullname
  
  --To Check for names for CRMS
  IF(CHARINDEX(';', @name) &gt; 0)
  SET @result = SUBSTRING(@name, 0, CHARINDEX(';', @name))
  
  ---To Check names for eGlobal
  ELSE
  SET @result = SUBSTRING(@name, 0, CHARINDEX(' ', @name))
  RETURN @result
  
  END
  GO
  </code></pre>
  
  <p>---Get Last Name</p>
  
  <pre><code>    CREATE FUNCTION [dbo].[GetLastName](@fullname varchar(30))
      RETURNS varchar(20)
      AS 
      BEGIN
  
  DECLARE @name nvarchar(30)
  DECLARE @result [nvarchar](30)
  SET @name = @fullname
  
  --To Check for names for CRMS
  IF(CHARINDEX(';', @name) &gt; 0)
  SET @result = SUBSTRING(@name, CHARINDEX(';', @name) + 1, LEN(@name) - CHARINDEX(';', @name));
  
  ---To Check names for eGlobal
  ELSE
  SET @result = SUBSTRING(@name, CHARINDEX(' ', @name) + 1, LEN(@name) - CHARINDEX(' ', @name));
  
  RETURN @result
  END
  GO
  </code></pre>
  
  <p></code></p>
  
  <p>This code is not working as I think I'm missing something. My understanding is CHARINDEX searches an character from the string and SUBSTRING can retrieve the part of the string for me.</p>
  
  <p>What I'm doing in the code is searching blank space (' ') using CHARINDEX and then getting it using SUBSTRING but its not working. Is this the right approach or can I refactor it more?</p>