fn_SplitPK.txt 1014 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. -- Input: a comma delimited list of integers like 1,4,9,16
  2. -- Output: the list split by the comma and put into a table
  3. -- This is designed for PK because it has a primary key.
  4. -- This is important for speed when joining with large tables.
  5. CREATE FUNCTION [fn_SplitPK]
  6. (
  7. @sDelimiter CHAR(1),
  8. @sList TEXT
  9. )
  10. RETURNS @tblList TABLE
  11. (
  12. Id INT NOT NULL,
  13. PRIMARY KEY(Id)
  14. )
  15. AS
  16. BEGIN
  17. DECLARE @iLoop INTEGER
  18. DECLARE @iStart INTEGER
  19. DECLARE @sLetter VARCHAR(1)
  20. SET @iLoop = 1
  21. SET @iStart = 1
  22. WHILE 1 = 1
  23. BEGIN
  24. SET @sLetter = SUBSTRING(@sList,@iLoop,1)
  25. IF ASCII(@sLetter) IS NULL
  26. BEGIN
  27. IF @iStart < @iLoop
  28. BEGIN
  29. INSERT INTO @tblList (Id)
  30. VALUES (CONVERT(INTEGER,SUBSTRING(@sList,@iStart,@iLoop- @iStart+1)))
  31. END
  32. BREAK
  33. END
  34. IF @sLetter = @sDelimiter
  35. BEGIN
  36. IF @iStart < @iLoop
  37. BEGIN
  38. INSERT INTO @tblList (Id)
  39. VALUES (CONVERT(INTEGER,SUBSTRING(@sList,@iStart,@iLoop - @iStart)))
  40. END
  41. SET @iStart = @iLoop + 1
  42. END
  43. SET @iLoop = @iLoop + 1
  44. END
  45. RETURN
  46. END