Tuesday, 25 July 2017

MSSQL - T-SQL equivalent of VBA VAL() function

There the text of scalar-value function to extract numbers from string and convert to integer:

IF OBJECT_ID(N'dbo.fn_extract_digits') IS NOT NULL
  DROP FUNCTION dbo.fn_extract_digits;
GO

CREATE FUNCTION dbo.fn_extract_digits (@str VARCHAR(MAX))
/*
https://yabele.blogspot.com/2017/07/mssql-t-sql-equivalent-of-vba-val.html
*/
RETURNS INT
AS
BEGIN
  DECLARE
    @newstr VARCHAR(MAX) = '',
    @i INT = 1,
    @chr CHAR(1);

  WHILE @i <= LEN(@str) BEGIN
    SET @chr = SUBSTRING(@str, @i, 1);
    IF @chr BETWEEN '0' AND '9'
      SET @newstr = @newstr + @chr;
    SET @i = @i + 1;
  END;

  RETURN CAST(@newstr AS INT);
END
/*
DECLARE @str VARCHAR(MAX) = '1-23-456';
SELECT Digits = dbo.fn_extract_digits(@str);*/
;