Frage

In SQL Server 2008 R2 I need to extract from a string everything between the character 50 and 60. I've searched for a similar function on the internet but didn't really find something which can address the problem.

I can do it on Excel with a formula like: MID(A2, 50, 10)

War es hilfreich?

Lösung

The sql function is called substring

  substring(fieldname,50,10)

Andere Tipps

If you need more flexibility, for instance if the separation does not occur in the same place each time you can use CHARINDEX. Here are a couple examples.

REVERSE(LEFT(REVERSE(fieldname),CHARINDEX(' ',REVERSE(fieldname))))

If your string is "AA 1235 A9" the output will be A9.

REPLACE(STUFF(fieldname,1,CHARINDEX('- ',fieldname),''),REVERSE(LEFT(REVERSE(fieldname),CHARINDEX(' ',REVERSE(fieldname)))),'')

Adding on to the first bit of code you can also pull the middle portion which will result in 1235. The ' ' is flexible and if there is a hyphen, asterisk or some other symbol/identifier you need to use then just use that instead of the space.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top