Well, I believe that this is what you need.
First, it uses a table value function, which is significantly faster than a Scalar or Multi-Statement table value function.
Secondly, for the Variable or Temporary Table, there was no need to use only some good odd row manipulations, a bit of math and CTE. Definitely not an expensive WHILE loop.
I tested this against the examples in the link, and they all returned the expected values.
USE Sandbox; GO CREATE FUNCTION ValidateHealthNumber (@HealthNumber varchar(10)) RETURNS TABLE AS RETURN WITH Doubles AS( SELECT CONVERT(tinyint,SUBSTRING(V.HN,OP,1)) AS HNDigit, CONVERT(tinyint,SUBSTRING(V.HN,OP,1)) * CASE WHEN OP % 2 = 0 THEN 1 ELSE 2 END ToAdd FROM (VALUES(@HealthNumber)) V(HN) CROSS APPLY (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9)) O(P)), Parts AS ( SELECT CONVERT(tinyint,SUBSTRING(CONVERT(varchar(2),ToAdd),1,1)) AS FirstDigit,
If you do not understand this, please ask.
Larnu
source share