I need sql query WITHOUT FUNCTION with SELECT only numeric characters.
For example, I have in sql table 0f-gh 14-2t-4 ///
and I want get this -> 01424
. How I can do it with sql query SELECT, without anything, only with SELECT
I need sql query WITHOUT FUNCTION with SELECT only numeric characters.
For example, I have in sql table 0f-gh 14-2t-4 ///
and I want get this -> 01424
. How I can do it with sql query SELECT, without anything, only with SELECT
Here is an inline approach
Declare @YourTable table (ID int,SomeCol varchar(max))
Insert Into @YourTable values
(1,'0f-gh 14-2t-4 ///')
Select A.ID
,B.*
From @YourTable A
Cross Apply (
Select NewValue = (Select substring(A.SomeCol,N,1)
From (Select Top (len(A.SomeCol)) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1) S
Where substring(A.SomeCol,N,1) like '[0-9]%'
Order By N
For XML Path (''))
) B
Returns
ID NewValue
1 01424
Note: Use Outer Apply
if you want to see null values in the event where the string has NO numerics.
This is the logic from digitsonlyEE which is the fastest T-SQL based "digits only" function available today.
declare @table table (somestring varchar(50));
insert @table VALUES('abc123xxx555!!!999'),('##123ttt999'),('555222!');
SELECT *
FROM @table t
CROSS APPLY
(
SELECT DigitsOnly =
(
SELECT SUBSTRING(t.somestring,n,1)
FROM
(
SELECT TOP (LEN(ISNULL(t.somestring,CHAR(32))))
(CHECKSUM(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))))
FROM
(VALUES ($),($),($),($),($),($),($),($),($),($)) a(x),
(VALUES ($),($),($),($),($),($),($),($),($),($)) b(x),
(VALUES ($),($),($),($),($),($),($),($),($),($)) c(x),
(VALUES ($),($),($),($),($),($),($),($),($),($)) d(x)
) iTally(n)
WHERE ((ASCII(SUBSTRING(t.somestring,N,1)) - 48) & 0x7FFF) < 10
FOR XML PATH('')
)
) digitsOnlyEE(digitsOnly);
Results:
somestring digitsOnly
--------------------- ----------
abc123xxx555!!!999 123555999
##123ttt999 123999
555222! 555222