Remove part of value in string with SQL server

Product:

Microsoft SQL azure

Issue:

In a view, we want to exclude all text in column “konto” after character ” – ”

Solution:

In the select statement use something like this:

IIF (SUBSTRING ([Konto],1, CHARINDEX (' - ',[Konto])) ='', [Konto] ,SUBSTRING ([Konto],1, CHARINDEX (' - ',[Konto]))) as [Konto]

 

Substring extract text in column konto from first position to where we find the – character, this position is given with charindex, and then we check if the result is empty. In case the string does not contain a -, then we get a empty value. Then we show the orginal value – otherwise we show the substring without all text after – in the field.

SUBSTRING(stringstartlength)

CHARINDEX(substringstringstart)

IIF(conditionvalue_if_truevalue_if_false)

More Information:

SUBSTRING, PATINDEX and CHARINDEX string functions in SQL queries

 

https://www.w3schools.com/sql/sql_isnull.asp

https://www.geeksforgeeks.org/sql/sql-statement-to-remove-part-of-a-string/

https://help.zebrabi.com/kb/power-bi/sort-a-hierarchy-by-custom-sort-logic/

https://www.w3schools.com/sql/func_sqlserver_substring.asp

https://www.w3schools.com/sql/func_sqlserver_iif.asp