2

In SQL Server 2008 R2 I have some data in a varchar(12) column, it looks something like this:

Data:
%%1234
%1765
34566
123
%SDRMH
HJG434

I'd like to drop the '%' from all the rows that have it and also only select those which are numbers. I've already tried to use the ISNUMERIC() function, but it looks like that leaves the % in the rows.

Any help is greatly appreciated.

MLorenzen
  • 69
  • 2
  • 8

4 Answers4

2

You can use a combination of REPLACE and ISNUMERIC to achieve the result set you want:

SELECT REPLACE(columnName,'%','') FROM tableName
WHERE ISNUMERIC(REPLACE(columnName,'%','')) = 1
steoleary
  • 8,968
  • 2
  • 33
  • 47
1

You could use the REPLACE function to strip out all the % instances

SELECT REPLACE(column_name,'%','');
GO
Mike
  • 2,391
  • 6
  • 33
  • 72
1

This function would be expensive to use, but it could help you create / populate a new column properly typed as an int (for example):

create function [dbo].[is_int]
    (   @value as varchar(max)  )
returns int
as
begin
declare @return int
set @return = 5
while len(@value) > 0
begin
    if left(@value,1) in('1','2','3','4','5','6','7','8','9','0')
        begin
            set @value = right(@value, len(@value)-1)
            set @return = 1
        end
    else
        begin
            set @return = 0
            set @value = ''
        end
end
return @return
end

or you could modify it to return the integers themselves, instead of a true/false (1/0).

Chains
  • 12,541
  • 8
  • 45
  • 62
0

You could do something like

SELECT REPLACE(column,'%','') WHERE ISNUMERIC(REPLACE(column,'%','')) = 1
user2989408
  • 3,127
  • 1
  • 17
  • 15