Once I was asked by my colleague to write a function which will add the numbers from a string, so I write a function for it. I used the TSQL substring, Len, ASCII and char functions to achieve this task.
Code Snippet:
Code Snippet:
CREATE FUNCTION SelectNumbersFromString(@str varchar(50)) RETURNS varchar(MAX) AS BEGIN DECLARE @cchk char(5); DECLARE @len int ; DECLARE @aschr int;
SET @len =
(SELECT len(@str)); DECLARE @count int
SET @count = 1 DECLARE @ans varchar(MAX)
SET @ans = '' While @count <= @len BEGIN
SET @cchk =
(SELECT Substring(@str,@count,1));
SET @aschr =
(SELECT ASCII(@cchk)); IF @aschr IN (49,
50,
51,
52,
53,
54,
55,
56,
57,
58) BEGIN
SET @ans = @ans + CHAR(@aschr) END
SET @count = @count + 1; END RETURN @ans; END