2

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.

lappy
  • 677
  • 3
  • 8
  • 15
  • Possible duplicate: http://stackoverflow.com/questions/106206/fastest-way-to-remove-non-numeric-characters-from-a-varchar-in-sql-server – Jon Schneider May 05 '15 at 14:51

4 Answers4

1

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)
sisve
  • 19,501
  • 3
  • 53
  • 95
1

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

gbn
  • 422,506
  • 82
  • 585
  • 676
0

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).

RBerman
  • 374
  • 4
  • 9
0

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
Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114