Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve only integer values from SQL Server [duplicate]

How to retrieve only the integer value from this column?

My table:

CREATE TABLE tbl_data (
    [Name] nvarchar(max)
)

INSERT INTO tbl_data VALUES
('Nikesh'),
('113'),
('sunam'),
('sudhir'),
('2.30'),
('ankit'),
('675')

Output I need:

Name
-----
113
675
like image 394
Ajit Kumar Avatar asked Oct 23 '16 10:10

Ajit Kumar


3 Answers

Taking both most upvoted answer on the duplicate target and removing a . from the code, plus a comment from that answer to Why are non-digits LIKE [0-9]?, the accurate answer to this question about integers is this:

SELECT Name
FROM tbl_data
WHERE Name NOT LIKE '%[^0123456789]%' COLLATE Latin1_General_CS_AS
like image 64
Vladimir Baranov Avatar answered Sep 22 '22 13:09

Vladimir Baranov


You can use XML.value:

;WITH tbl_data AS (
SELECT *
FROM (VALUES
('Nikesh'),
('113'),
('sunam'),
('sudhir'),
('2.30'),
('ankit'),
('675')
) as t([Name])
)

SELECT *
FROM tbl_data
WHERE CAST([Name] as xml).value('. cast as xs:integer?','int') IS NOT NULL

Output:

Name
113
675
like image 23
gofr1 Avatar answered Sep 22 '22 13:09

gofr1


Select name from tbl_data where Isnumeric(name) = 1 and name not like '%.%'
like image 23
Hadi Avatar answered Sep 24 '22 13:09

Hadi