Delete the last two characters of a sql server string

2

I use SQL Server 2000 and I have a table with a field rut of type VARCHAR (eg: '17045782-8' I need: '17045782') to which I have to remove the check digit and the hyphen. And I do not find it with substring(rut,0,x) since the length of the rut until before the script is variable.

How can I do it?

    
asked by daniel2017- 24.03.2017 в 14:55
source

1 answer

6

For this you can simply use CHARINDEX to find the position of the script:

SELECT Rut, 
       LEFT(Rut,CHARINDEX('-',Rut)-1) Rut_Sin_DV
FROM dbo.YourTable;

If there is data that does not have a script, the previous solution will throw an error. To avoid these cases, you can use the following:

SELECT Rut, 
       CASE 
           WHEN CHARINDEX('-',Rut) > 0 THEN LEFT(Rut,CHARINDEX('-',Rut)-1) 
           ELSE Rut
       END Rut_Sin_DV
FROM dbo.YourTable;
    
answered by 24.03.2017 / 15:02
source