Select substring of retrieved value - sql

Consider the following table:
MyValue
--------------------
123
122_DELETED
45670
42425
43_NO_VIEW
4365463_CORRUPT
53
4335_NO_VIEW_ALLOWED
I'm trying to get only the numbers returned. In other words: string everything after the first underscore (_):
select
left(MyValue, charindex(('_', MyValue)-1)
from
DB.Table
However, this returns the error Invalid length parameter passed to the LEFT or SUBSTRING function. I believe this is because the value is NULL in case the current value has no underscore (for instance, 123).
How can I account for this exception? Any help is greatly appreciated.
I am on SQL Server 2008.

try this!
select myval,case when myval like '%[_]%' then
substring(myval,1,patindex('%[_]%',myval)-1) else myval end from t
##DEMO USING PATINDEX
##DEMO USING CHARINDEX

select SUBSTRING(MyValue,CHARINDEX('_',MyValue)+1,LEN(MyValue)) from DB.Table

try this
select
case when MyValue is null then '' --if null return empty string
when charindex('_', MyValue) > 0 then
left(MyValue, charindex('_', MyValue)-1)
else
MyValue --Return the field value if an underscore is not present
end as Result
from
DB.Table

Try out this one:
declare #st varchar(20)
set #st ='4365463_CORRU'
select #st, SUBSTRING(#st,CHARINDEX('_',#st)-LEN(#st),LEN(#st))

Check this .
declare #t table (myvalue varchar(50))
insert into #t
values ( '123'),('122_DELETED'),('45670'),('42425'),('43_NO_VIEW'),('4365463_CORRUPT'),('53'),('4335_NO_VIEW_ALLOWED')
select * from #t
;With cte as
(
select CHARINDEX( '_', myvalue)+1 d , myvalue from #t
)
select SUBSTRING(myvalue,d,LEN(myvalue) ) from cte

Related

how to check and change custom string in sql server

i have problem in my sql query code
i have one column for my codes and structure of code like this
3digit-1to3digit-5to7digit-1to2digit
xxx-xxx-xxxxxx-xx
in code column user add code like
1-1486414-305-115 --mistake
116-500-325663-1 --ok
116-2-2244880-1 --ok
121-512-2623075-1 --ok
122-500-1944261-3 --ok
2-2651274-500-147 --mistake
1-2551671-305-147 --mistake
124-500-329130-1 --ok
how to check and fix the mistake codes.
thanks for read my problem
Alternatively, instead of a load of LIKE expressions, you could split the parts and inspect their lengths, and follow up by checking the string only contains digits and hyphens with a LIKE. As your string specifically has 4 parts, I've used PARSENAME here, rather than a "splitter" function.
SELECT *
FROM (VALUES ('1-1486414-305-115'),
('116-500-325663-1'),
('116-2-2244880-1'),
('121-512-2623075-1'),
('122-500-1944261-3'),
('2-2651274-500-147'),
('1-2551671-305-147'),
('116-ba-2244880-1'),
('124-500-329130-1'))V(Code)
CROSS APPLY (VALUES(PARSENAME(REPLACE(V.code,'-','.'),4),
PARSENAME(REPLACE(V.code,'-','.'),3),
PARSENAME(REPLACE(V.code,'-','.'),2),
PARSENAME(REPLACE(V.code,'-','.'),1))) PN(P1, P2, P3, P4)
WHERE LEN(P1) != 3
OR NOT(LEN(P2) BETWEEN 1 AND 3)
OR NOT(LEN(P3) BETWEEN 5 AND 7)
OR NOT(LEN(P4) BETWEEN 1 AND 2)
OR V.Code LIKE '%[^0-9\-]%' ESCAPE '\';
What a pain, because SQL Server does not support regular expressions.
One method is 6 like comparisons:
where col like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9]' or
col like '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9]'
Otherwise, you could count the -s, check the positions, and characters. So:
where col not like '[^-0-9]' and -- only has digits and -
col not like '%-%-%-%-%' and -- does not have 4 hyphens
col like '___-___-%-%[0-9]' and -- first two hyphens in the right place and ends in digit
'-' in (substring(col, 14, 1), substring(col, 15, 1), substring(col, 16, 1)) -- last hyphen in the right place
Here is the complete code which can achieve the required result
1) store the splitted string into a table #myvalues (I have written a solution to split a string into many rows using Recusrsivity in this Link )
2) Store the conditions in Table #tabcheck (length of each string)
3) Make a jointure between #myvalues and #tabcheck to get the result
declare #str as nvarchar(max)
set #str='116-500-325663-1';
declare #separator as char(1)
set #separator='-';
declare #tabcheck as table(id int,fromval int ,toval int)
insert into #tabcheck values(1,3,3),(2,1,3),(3,5,7),(4,1,2);
declare #myvalues as table(id int identity(1,1),myval varchar(100));
with cte as(
select #str [mystr],
cast(1 as int) [Start],
charindex(#separator,#str)as Nd
union all
select substring(#str,nd+1,len(#str)),cast(Nd+1 as int),charindex(#separator,#str,Nd+1) from cte
where nd>0
)
insert into #myvalues(myval)
select case when nd>0 then substring(#str,start,Nd-start)
else substring(#str,start,len(#str)) end [splitted]
from cte OPTION (MAXRECURSION 1000);
declare #result as int;
with mytab as(
select t1.id,t1.myval,len(t1.myval) L,t2.fromval,t2.toval,
case when len(t1.myval)>=t2.fromval and len(t1.myval)<=t2.toval then 1 else 0 end [result]
from #myvalues t1 inner join #tabcheck t2 on t1.id=t2.id)
select #result=count(1) from mytab where result=0 ;
select case #result when 0 then 'OK' else 'Mistake' end [result]

how to make a left space in a nchar(2) word? [duplicate]

I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id values with zero's:
id
----
0001
0002
0012
0123
1234
How can I achieve this?
I believe this may be what your looking for:
SELECT padded_id = REPLACE(STR(id, 4), SPACE(1), '0')
FROM tableA
or
SELECT REPLACE(STR(id, 4), SPACE(1), '0') AS [padded_id]
FROM tableA
I haven't tested the syntax on the 2nd example. I'm not sure if that works 100% - it may require some tweaking - but it conveys the general idea of how to obtain your desired output.
EDIT
To address concerns listed in the comments...
#pkr298 - Yes STR does only work on numbers... The OP's field is an ID... hence number only.
#Desolator - Of course that won't work... the First parameter is 6 characters long. You can do something like:
SELECT REPLACE(STR(id,
(SELECT LEN(MAX(id)) + 4 FROM tableA)), SPACE(1), '0') AS [padded_id] FROM tableA
this should theoretically move the goal posts... as the number gets bigger it should ALWAYS work.... regardless if its 1 or 123456789...
So if your max value is 123456... you would see 0000123456 and if your min value is 1 you would see 0000000001
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
declare #T table(id int)
insert into #T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from #T
Result
----
0001
0002
0012
0123
1234
Try this:
SELECT RIGHT(REPLICATE('0',4)+CAST(Id AS VARCHAR(4)),4) FROM [Table A]
-- Please look into these.
select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');
-- I hope these would help you
This works for strings, integers and numeric:
SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)
Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.
If someone is still interested, I found this article on DATABASE.GUIDE:
Left Padding in SQL Server – 3 LPAD() Equivalents
In short, there are 3 methods mentioned in that article.
Let's say your id=12 and you need it to display as 0012.
Method 1 – Use the RIGHT() Function
The first method uses the RIGHT() function to return only the rightmost part of the string, after adding some leading zeros.
SELECT RIGHT('00' + '12', 4);
Result:
0012
Method 2 – Use a Combination of RIGHT() and REPLICATE()
This method is almost the same as the previous method, with the only difference being that I simply replace the three zeros with the REPLICATE() function:
SELECT RIGHT(REPLICATE('0', 2) + '12', 4);
Result:
0012
Method 3 – Use a Combination of REPLACE() and STR()
This method comes from a completely different angle to the previous methods:
SELECT REPLACE(STR('12', 4),' ','0');
Result:
0012
Check out the article, there is more in depth analysis with examples.
This is what I normally use when I need to pad a value.
SET #PaddedValue = REPLICATE('0', #Length - LEN(#OrigValue)) + CAST(#OrigValue as VARCHAR)
I created a function to do this, where you can specify the desired output character length:
CREATE FUNCTION [dbo].[udfLeadingZero]
(
#String VARCHAR(MAX)
, #Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
SET #String = RIGHT(REPLICATE('0',#Len)+#String,#Len)
RETURN #String
END
GO
Example results
I needed this in a function on SQL server and adjusted Patrick's answer a bit.
declare #dossierId int = 123
declare #padded_id varchar(7)
set #padded_id = REPLACE(
SPACE(7 - LEN(#dossierId)) + convert(varchar(7), #dossierId),
SPACE(1),
'0')
SELECT #dossierId as '#dossierId'
,SPACE(LEN(#dossierId)) + convert(varchar(7)
,#dossierId) as withSpaces
,#padded_id as '#padded_id'
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
#Text NVARCHAR(MAX) ,
#Replace NVARCHAR(MAX) ,
#Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #var NVARCHAR(MAX)
SELECT #var = ISNULL(LTRIM(RTRIM(#Text)) , '')
RETURN RIGHT(REPLICATE(#Replace,#Len)+ #var, #Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](#int int, #Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE #strInt varchar(255)
SET #strInt = CAST(#int as varchar(255))
RETURN (REPLICATE('0', (#Length - LEN(#strInt))) + #strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Something fairly ODBC compliant if needed might be the following:
select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
+ cast (FIELD as varchar(10))
from TABLE_NAME
This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare #minlen int = 6
declare #str varchar(20)
set #str = '123'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 000123
set #str = '1234'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 001234
set #str = '123456'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = 'NEFT 123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: NEFT 123456789
A simple example would be
DECLARE #number INTEGER
DECLARE #length INTEGER
DECLARE #char NVARCHAR(10)
SET #number = 1
SET #length = 5
SET #char = '0'
SELECT FORMAT(#number, replicate(#char, #length))
More efficient way is :
Select id, LEN(id)
From TableA
Order by 2,1
The result :
id
----
1
2
12
123
1234

What T-SQL statement can add leading zeros to a column of numbers? [duplicate]

I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id values with zero's:
id
----
0001
0002
0012
0123
1234
How can I achieve this?
I believe this may be what your looking for:
SELECT padded_id = REPLACE(STR(id, 4), SPACE(1), '0')
FROM tableA
or
SELECT REPLACE(STR(id, 4), SPACE(1), '0') AS [padded_id]
FROM tableA
I haven't tested the syntax on the 2nd example. I'm not sure if that works 100% - it may require some tweaking - but it conveys the general idea of how to obtain your desired output.
EDIT
To address concerns listed in the comments...
#pkr298 - Yes STR does only work on numbers... The OP's field is an ID... hence number only.
#Desolator - Of course that won't work... the First parameter is 6 characters long. You can do something like:
SELECT REPLACE(STR(id,
(SELECT LEN(MAX(id)) + 4 FROM tableA)), SPACE(1), '0') AS [padded_id] FROM tableA
this should theoretically move the goal posts... as the number gets bigger it should ALWAYS work.... regardless if its 1 or 123456789...
So if your max value is 123456... you would see 0000123456 and if your min value is 1 you would see 0000000001
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
declare #T table(id int)
insert into #T values
(1),
(2),
(12),
(123),
(1234)
select right('0000'+convert(varchar(4), id), 4)
from #T
Result
----
0001
0002
0012
0123
1234
Try this:
SELECT RIGHT(REPLICATE('0',4)+CAST(Id AS VARCHAR(4)),4) FROM [Table A]
-- Please look into these.
select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');
-- I hope these would help you
This works for strings, integers and numeric:
SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)
Where 4 is desired length. Works for numbers with more than 4 digits, returns empty string on NULL value.
If someone is still interested, I found this article on DATABASE.GUIDE:
Left Padding in SQL Server – 3 LPAD() Equivalents
In short, there are 3 methods mentioned in that article.
Let's say your id=12 and you need it to display as 0012.
Method 1 – Use the RIGHT() Function
The first method uses the RIGHT() function to return only the rightmost part of the string, after adding some leading zeros.
SELECT RIGHT('00' + '12', 4);
Result:
0012
Method 2 – Use a Combination of RIGHT() and REPLICATE()
This method is almost the same as the previous method, with the only difference being that I simply replace the three zeros with the REPLICATE() function:
SELECT RIGHT(REPLICATE('0', 2) + '12', 4);
Result:
0012
Method 3 – Use a Combination of REPLACE() and STR()
This method comes from a completely different angle to the previous methods:
SELECT REPLACE(STR('12', 4),' ','0');
Result:
0012
Check out the article, there is more in depth analysis with examples.
This is what I normally use when I need to pad a value.
SET #PaddedValue = REPLICATE('0', #Length - LEN(#OrigValue)) + CAST(#OrigValue as VARCHAR)
I created a function to do this, where you can specify the desired output character length:
CREATE FUNCTION [dbo].[udfLeadingZero]
(
#String VARCHAR(MAX)
, #Len INT
)
RETURNS VARCHAR(MAX)
BEGIN
SET #String = RIGHT(REPLICATE('0',#Len)+#String,#Len)
RETURN #String
END
GO
Example results
I needed this in a function on SQL server and adjusted Patrick's answer a bit.
declare #dossierId int = 123
declare #padded_id varchar(7)
set #padded_id = REPLACE(
SPACE(7 - LEN(#dossierId)) + convert(varchar(7), #dossierId),
SPACE(1),
'0')
SELECT #dossierId as '#dossierId'
,SPACE(LEN(#dossierId)) + convert(varchar(7)
,#dossierId) as withSpaces
,#padded_id as '#padded_id'
Create Function :
Create FUNCTION [dbo].[PadLeft]
(
#Text NVARCHAR(MAX) ,
#Replace NVARCHAR(MAX) ,
#Len INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE #var NVARCHAR(MAX)
SELECT #var = ISNULL(LTRIM(RTRIM(#Text)) , '')
RETURN RIGHT(REPLICATE(#Replace,#Len)+ #var, #Len)
END
Example:
Select dbo.PadLeft('123456','0',8)
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](#int int, #Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE #strInt varchar(255)
SET #strInt = CAST(#int as varchar(255))
RETURN (REPLICATE('0', (#Length - LEN(#strInt))) + #strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Something fairly ODBC compliant if needed might be the following:
select ifnull(repeat('0', 5 - (floor(log10(FIELD_NAME)) + 1)), '')
+ cast (FIELD as varchar(10))
from TABLE_NAME
This bases on the fact that the amount of digits for a base-10 number can be found by the integral component of its log. From this we can subtract it from the desired padding width. Repeat will return null for values under 1 so we need ifnull.
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare #minlen int = 6
declare #str varchar(20)
set #str = '123'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 000123
set #str = '1234'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 001234
set #str = '123456'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = '123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: 123456789
set #str = 'NEFT 123456789'
select case when len(#str) < #minlen then REPLICATE('0',#minlen-len(#str))+#str else #str end
--Ans: NEFT 123456789
A simple example would be
DECLARE #number INTEGER
DECLARE #length INTEGER
DECLARE #char NVARCHAR(10)
SET #number = 1
SET #length = 5
SET #char = '0'
SELECT FORMAT(#number, replicate(#char, #length))
More efficient way is :
Select id, LEN(id)
From TableA
Order by 2,1
The result :
id
----
1
2
12
123
1234

Truncating leading zeros in sql server

I need to represent the following records
DATA
000200AA
00000200AA
000020BCD
00000020BCD
000020ABC
AS
DATA CNT
200AA 1
20BCD 2
20ABC 2
ANY IDEAS?
USE patindex
select count(test) as cnt,
substring(test, patindex('%[^0]%',test),len(test)) from (
select ('000200AA') as test
union
select '00000200AA' as test
union
select ('000020BCD') as test
union
select ('00000020BCD') as test
union
select ('000020ABC') as test
)ty
group by substring(test, patindex('%[^0]%',test),len(test))
How about a nice recursive user-defined function?
CREATE FUNCTION dbo.StripLeadingZeros (
#input varchar(MAX)
) RETURNS varchar(MAX)
BEGIN
IF LEN(#input) = 0
RETURN #input
IF SUBSTRING(#input, 1, 1) = '0'
RETURN dbo.StripLeadingZeros(SUBSTRING(#input, 2, LEN(#input) - 1))
RETURN #input
END
GO
Then:
SELECT dbo.StripLeadingZeros(DATA) DATA, COUNT(DATA) CNT
FROM YourTable GROUP BY dbo.StripLeadingZeros(DATA)
DECLARE #String VARCHAR(32) = N'000200AA'
SELECT SUBSTRING ( #String ,CHARINDEX(N'2', #String),LEN(#String))
Depending on the what you need to get the values this code may differ:
Assuming a simple right 5 chars as Barry suggested, you can use RIGHT(data, 5) and GROUP BY and COUNT to get your results
http://sqlfiddle.com/#!3/19ecd/2
take a look at the STUFF function
It inserts data into a string on a range
You can do this query:
SELECT RIGHT([DATA],LEN[DATA])-PATINDEX('%[1-9]%',[DATA])+1) [DATA], COUNT(*) CNT
FROM YourTable
GROUP BY RIGHT([DATA],LEN[DATA])-PATINDEX('%[1-9]%',[DATA])+1)

sql like operator to get the numbers only

This is I think a simple problem but not getting the solution yet. I would like to get the valid numbers only from a column as explained here.
Lets say we have a varchar column with following values
ABC
Italy
Apple
234.62
2:234:43:22
France
6435.23
2
Lions
Here the problem is to select numbers only
select * from tbl where answer like '%[0-9]%' would have done it but it returns
234.62
2:234:43:22
6435.23
2
Here, obviously, 2:234:43:22 is not desired as it is not valid number.
The desired result is
234.62
6435.23
2
Is there a way to do this?
You can use the following to only include valid characters:
SQL
SELECT * FROM #Table
WHERE Col NOT LIKE '%[^0-9.]%'
Results
Col
---------
234.62
6435.23
2
You can try this
ISNUMERIC (Transact-SQL)
ISNUMERIC returns 1 when the input
expression evaluates to a valid
numeric data type; otherwise it
returns 0.
DECLARE #Table TABLE(
Col VARCHAR(50)
)
INSERT INTO #Table SELECT 'ABC'
INSERT INTO #Table SELECT 'Italy'
INSERT INTO #Table SELECT 'Apple'
INSERT INTO #Table SELECT '234.62'
INSERT INTO #Table SELECT '2:234:43:22'
INSERT INTO #Table SELECT 'France'
INSERT INTO #Table SELECT '6435.23'
INSERT INTO #Table SELECT '2'
INSERT INTO #Table SELECT 'Lions'
SELECT *
FROM #Table
WHERE ISNUMERIC(Col) = 1
Try something like this - it works for the cases you have mentioned.
select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'
With SQL 2012 and later, you could use TRY_CAST/TRY_CONVERT to try converting to a numeric type, e.g. TRY_CAST(answer AS float) IS NOT NULL -- note though that this will match scientific notation too (1+E34). (If you use decimal, then scientific notation won't match)
what might get you where you want in plain SQL92:
select * from tbl where lower(answer) = upper(answer)
or, if you also want to be robust for leading/trailing spaces:
select * from tbl where lower(answer) = trim(upper(answer))