tags:

views:

86

answers:

3

I want to remove a particular character while retrieving a varchar from a table. The query looks like this:

SELECT ServiceName,
       case isNumeric(Ramusage) 
         when 1 then 
           cast ( ltrim ( rtrim ( ramusage )) as int )
         else 
           0 
       end as test,
       priority
  FROM ProcessInfo

Here the problem is the ramusage is a varchar and it stores values like 12,500K, 4,321K.

Here i want to remove the k from the entry and display the number alone.

A: 
substr( ltrim( rtrim( ramusage ) ), length( ramusage ) - 1)

edit: replace, as mentionned in the answers below, is prolly better.

Natrium
+2  A: 

Use REPLACE

DECLARE @ProcessInfo TABLE(
     ServiceName VARCHAR(MAX),
     Ramusage VARCHAR(MAX),
     priority INT
)

INSERT INTO @ProcessInfo (ServiceName,Ramusage,priority)
SELECT 'TEST','12,123K',1

SELECT ServiceName,
       case isNumeric(REPLACE(REPLACE(Ramusage,'K',''),',','')) 
         when 1 then 
           cast ( ltrim ( rtrim ( REPLACE(REPLACE(Ramusage,'K',''),',',''))) as int )
         else 
           0 
       end as test,
       priority
  FROM @ProcessInfo

what we have done is to create a CLR function to take a string amd remove all non numeric items

[Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString RemoveNonNumeric(SqlString strValue)
    {
        string strNew = strValue.ToString();

        char[] chrArray = strNew.ToCharArray();

        strNew = null;

        for (int iChar = 0; iChar < chrArray.Length; iChar++)
        {
            if (Char.IsNumber(chrArray[iChar]))
                strNew += chrArray[iChar];
        }

        // Put your code here
        return new SqlString(strNew);
    }
astander
If dealing with SQL Server 2005+, I'd do the REPLACE stuff in a CTE.
OMG Ponies
we have played around alot with a couple of ideas, one of our transaction tables have a foreign transaction ref, and testing with just over 4 mil records, we found that the clr function was the fastest.. (also sql server 2005)
astander
+2  A: 

You want to use the REPLACE function:

REPLACE(ramusage, 'k', '')

Reference:

OMG Ponies
thanks a lot it worked