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:

  1. IF OBJECT_ID(N'dbo.fn_extract_digits') IS NOT NULL
  2. DROP FUNCTION dbo.fn_extract_digits;
  3. GO
  4.  
  5. CREATE FUNCTION dbo.fn_extract_digits (@str VARCHAR(MAX))
  6. /*
  7. https://yabele.blogspot.com/2017/07/mssql-t-sql-equivalent-of-vba-val.html
  8. */
  9. RETURNS INT
  10. AS
  11. BEGIN
  12. DECLARE
  13. @newstr VARCHAR(MAX) = '',
  14. @i INT = 1,
  15. @chr CHAR(1);
  16.  
  17. WHILE @i <= LEN(@str) BEGIN
  18. SET @chr = SUBSTRING(@str, @i, 1);
  19. IF @chr BETWEEN '0' AND '9'
  20. SET @newstr = @newstr + @chr;
  21. SET @i = @i + 1;
  22. END;
  23.  
  24. RETURN CAST(@newstr AS INT);
  25. END
  26. /*
  27. DECLARE @str VARCHAR(MAX) = '1-23-456';
  28. SELECT Digits = dbo.fn_extract_digits(@str);*/
  29. ;

No comments:

Post a Comment

Note: only a member of this blog may post a comment.