Removing non-numeric characters in T-SQL

2019-07-08 10:15发布

I'm using the function sp_spaceused to get the details of all the tables in a DB. The index_size column is VARCHAR returned complete with ' KB' on the end, however I want to to display in MB. All I need to know is how to strip out the KB, I can do the rest! :D

UPDATE: I don't feel this is a duplicate of the other question suggested as I was looking for a SQL only solution, which was given in this thread.

标签: tsql varchar
4条回答
Evening l夕情丶
2楼-- · 2019-07-08 10:23

My first thought would be to just store in in a variable and just use substring to remove the last characters.

-- Setup
DECLARE @data VARCHAR(50)
SET @data = '159736 KB'

-- Computation
SET @data = SUBSTRING(@data, 1, LEN(@data)-2)

-- Conversion
SELECT CAST(@data AS INTEGER)
查看更多
smile是对你的礼貌
3楼-- · 2019-07-08 10:31

REPLACE(column, 'KB', ''). No need for LEN and other stuff

On SQL 2005, this will give you the "reserved" value:

SELECT
    SUM(au.total_pages) / 128.0 AS UsedMB
FROM
    sys.allocation_units au

Some more investigation should allow you to read index vs data space out of the catlog views too

查看更多
贪生不怕死
4楼-- · 2019-07-08 10:32

More generic solution:

-- Test data
DECLARE @StrIn VARCHAR(100), @StrOut VARCHAR(100), @I INT, @Len INT
  SELECT @StrIn = '123m43 5m409', @StrOut = '', @I = 0, @Len = Len(@StrIn)

-- Answer
WHILE (@I < @Len) BEGIN 
  SELECT @I = @I + 1, 
    @StrOut = @StrOut + 
      CASE 
        WHEN (CAST(ASCII(SUBSTRING(@StrIn, @I, 1)) AS INT) BETWEEN 47 AND 58) 
        THEN SUBSTRING(@StrIn, @I, 1) ELSE '' 
      END 
END

SELECT @StrIn, @StrOut
查看更多
欢心
5楼-- · 2019-07-08 10:47

General solution for T-SQL (SS 2008+), to remove all but a set of allowed characters:

DECLARE @StrIn varchar(20)='(323)-555-1212'; -- input value    
DECLARE @Allowed varchar(20)='%[0123456789]%'; -- pattern for allowed characters.

DECLARE @Result varchar(20)=''; -- result    
DECLARE @I int = patindex(@Allowed, @StrIn);

WHILE (@I>0)
begin

    SET @Result = @Result + SUBSTRING(@StrIn, @I, 1); -- add allowed charcter.
    set @StrIn = SUBSTRING(@StrIn, @I+1, 20); -- take rest of string.
    SET @i = patindex(@Allowed, @StrIn); 
END

PRINT @Result;

This could easily be encapsulated into a scalar function. A completely general function would accept the list of characters allowed, or you could hard-code for special purpose (like this one).

查看更多
登录 后发表回答