sql server - How to grab everything before a 3rd occurrence of a character in SQL query -
how can grab data before 3rd '-'? below have sample data:
000700- - - 8 015111- - 005 - 019999- - 005 - a01- 01200- 0 - 5 a01-012000- - 5 a02-015450- - 5 a02-015450- 003 - 1 d08-020700- - 8 d08-020710- - 5 d08-020710- 013 - 1 d08-020710- 013 - 3
this have done , proper info. because there spaces missing being removed cannot proper comparison data in crystal reports.
reverse(substring(reverse(a.projectioncode), charindex('-', reverse(a.projectioncode)) + 1, len(reverse(a.projectioncode))))) phasecode
this should need , work in event there more or less 3 dashes given row.
-- test data... insert #testdata (somestring) values ('000700- - - 8'), ('015111- - 005 -'), ('019999- - 005 -'), ('a01- 01200- 0 - 5'), ('a01-012000- - 5'), ('a02-015450- - 5'), ('a02-015450- 003 - 1'), ('d08-020700- - 8'), ('d08-020710- - 5'), ('d08-020710- 013 - 1'), ('d08-020710- 013 - 3'), ('1-2-3-4-5-6-7-8-9'), -- more 3 dashes ('zaq12wsx-vfr445tgb'), -- lesst 3 dashes ('987654321345678'); -- no dashes -- query... select td.somestring, left(td.somestring, isnull(d3.dash, len(td.somestring) + 1)- 1) #testdata td cross apply ( values (nullif(charindex('-', td.somestring, 1), 0)) ) d1 (dash) cross apply ( values (nullif(charindex('-', td.somestring, d1.dash + 1), 0)) ) d2 (dash) cross apply ( values (nullif(charindex('-', td.somestring, d2.dash + 1), 0)) ) d3 (dash);
edit: adding function , usage code...
itvf
create function dbo.tfn_textleftofthirddash /* ============================================================================================= itvf returns text left og 3rd dash in string of text ============================================================================================= */ ( @string varchar(8000) ) returns table schemabinding return select stringremain = left(@string, isnull(d3.dash, len(@string) + 1)- 1) ( values (nullif(charindex('-', @string, 1), 0)) ) d1 (dash) cross apply ( values (nullif(charindex('-', @string, d1.dash + 1), 0)) ) d2 (dash) cross apply ( values (nullif(charindex('-', @string, d2.dash + 1), 0)) ) d3 (dash); go
how use function...
select td.somestring, l3d.stringremain #testdata td cross apply dbo.tfn_textleftofthirddash(td.somestring) l3d;
hth, jason
Comments
Post a Comment