June 11, 2018 at 12:53 pm
HI Friends ,I have one doubt in sql server .
how to remove only numeric only in the given string.
sample data
declare @t table (a varchar(50))
insert into @t values ('Nxyz_tV_201806040918')
insert into @t values ('av_OrV_rW_20180604000000')
insert into @t values ('xt_tNT_tW_20180531_xyz')
insert into @t values ('c:\abc_Pun_yb_20180604000000')
insert into @t values ('c:\Uj_To_EDW_20180531_sr')
insert into @t values ('c:\USFC_TRN_EDW_20180604000000_tx')
expected output like below:
Nxyz_tV
av_OrV_rW
xt_tNT_tW_xyz
c:\abc_Pun_yb
c:\Uj_To_EDW_sr
c:\USFC_TRN_EDW_tx
I tried like below:
SELECT LEFT(a, LEN(a) - CHARINDEX('_',REVERSE(a)))
FROM @t
another way I tried
SELECT
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (a, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '')
FROM @t
above query is not given expected result.
please tell me how to write query to achive this task in sql server .
June 11, 2018 at 1:34 pm
Combine your 2 statements like this ....SELECT a = LEFT(a, LEN(a) - CHARINDEX('_',REVERSE(a)))
FROM (
SELECT
REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (a, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', ''),
'__', '_') as a
FROM @t
) AS src
June 11, 2018 at 1:58 pm
Not really a suggestion because the solution posted by DesNorton should be better but I just wanted to have some fun.
SELECT * ,
STUFF(( SELECT '_' + dsk.Item
FROM dbo.DelimitedSplit8K(t.a, '_') AS dsk
WHERE dsk.Item LIKE '%[^0-9]%'
FOR XML PATH(''), TYPE).value('./text()[1]', 'varchar(max)'), 1, 1, '')
FROM @t AS t
June 11, 2018 at 6:10 pm
SELECT SUBSTRING(a,0,PATINDEX('%[0-9]%',a)-1) + REVERSE(SUBSTRING(REVERSE(a),0,PATINDEX('%[0-9]%',REVERSE(a)))) AS A
FROM #t
June 11, 2018 at 7:31 pm
Is there any guarantee that ALL of the numeric characters will ALWAYS be contiguous in EVERY string?
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply