Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LastIndexOf and SubString in mssql

How do I get [Result] column from [Code] column using ms sql

Id          Code
200001      43791
200001      67036
200006      19.09.01.08683      
200006      03.01.04.01.64230   
200007      19.01.03.02804    

Id          Result  Code
200001      43791   43791
200001      67036   67036
200006      08683   19.09.01.08683      
200006      64230   03.01.04.01.64230   
200007      02804   19.01.03.02804    
like image 213
Onuralp Avatar asked Nov 28 '12 16:11

Onuralp


People also ask

Is there a Lastindexof in SQL Server?

Yes, that is the purpose.

Can we use substring in where clause in SQL?

The SUBSTRING SQL function is very useful when you want to make sure that the string values returned from a query will be restricted to a certain length. In the following example, using the 'firstname' column, the last two characters are matched with the word 'on' using the SQL SUBSTRING function in the where clause.

How do I get the last position of a character in a string in SQL?

If you want to get the index of the last space in a string of words, you can use this expression RIGHT(name, (CHARINDEX(' ',REVERSE(name),0)) to return the last word in the string.


1 Answers

SELECT Id,
       RIGHT(Code, CHARINDEX('.', REVERSE('.' + Code)) - 1) AS [Result],
       Code
FROM   YourTable 
like image 152
Martin Smith Avatar answered Oct 22 '22 17:10

Martin Smith