Go to content Go to navigation and search

Home

Current SQL Server Blog Articles


Search

Browse

RSS / Atom

Email me

textpattern

Creative Commons License
All Blog Articles, Data Models and Free Source Code by Simon Greener, The SpatialDB Advisor is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

generate_series for SQL Server 2008

Monday April 09 2012 at 23:36

A few years ago I wrote an article about implementing the PostgreSQL function, generate_series, in Oracle. This function is really useful for when trying to write SQL/Functions that can be implemented across one or more databases with reasonable ease.

Here is the function implemented in SQL Server 2008:

  1. -- Connect to database holding generate_series
  2. --
  3. USE [GISDB] -- Change to your database
  4. GO
  5. -- Drop function if exists
  6. --
  7. IF EXISTS (SELECT *
  8.              FROM dbo.sysobjects
  9.             WHERE id = object_id (N'[dbo].[generate_series]')
  10.               AND OBJECTPROPERTY(id, N'IsTableFunction') = 1)
  11. DROP FUNCTION [dbo].[generate_series]
  12. GO
  13. --
  14. -- Now let's create it
  15. --
  16. CREATE FUNCTION [dbo].[generate_series] ( @p_start INT, @p_end INT, @p_step INT=1 )
  17. RETURNS @Integers TABLE ( [IntValue] INT )
  18. AS
  19. BEGIN
  20.     DECLARE
  21.       @v_i                 INT,
  22.       @v_step              INT,
  23.       @v_terminating_value INT;
  24.     BEGIN
  25.       SET @v_i = CASE WHEN @p_start IS NULL THEN 1 ELSE @p_start END;
  26.       SET @v_step  = CASE WHEN @p_step IS NULL OR @p_step = 0 THEN 1 ELSE @p_step END;
  27.       SET @v_terminating_value =  @p_start + CONVERT(INT,ABS(@p_start-@p_end) / ABS(@v_step) ) * @v_step;
  28.       -- Check for impossible combinations
  29.       IF NOT ( ( @p_start > @p_end AND SIGN(@p_step) = 1 )
  30.                OR
  31.                ( @p_start < @p_end AND SIGN(@p_step) = -1 ))
  32.       BEGIN
  33.         -- Generate values
  34.         WHILE ( 1 = 1 )
  35.         BEGIN
  36.            INSERT INTO @Integers ( [IntValue] ) VALUES ( @v_i )
  37.            IF ( @v_i = @v_terminating_value )
  38.               BREAK
  39.            SET @v_i = @v_i + @v_step;
  40.         END;
  41.       END;
  42.     END;
  43.     RETURN
  44. END
  45. GO

Now, let’s test this function.

  1. -- Simple increment by 1
  2. SELECT g.IntValue AS generate_series
  3.   FROM generate_series(2,4,1) g;
  4. -- Results
  5. generate_series
  6. 2
  7. 3
  8. 4
  9. -- Increment using Default value (1)
  10. SELECT g.IntValue AS generate_series
  11.   FROM generate_series(1,5,DEFAULT) g;
  12. -- Results
  13. generate_series
  14. 1
  15. 2
  16. 3
  17. 4
  18. 5
  19. -- Increase in steps of 10
  20. SELECT g.IntValue AS generate_series
  21.   FROM [generate_series] ( 100, 200, 10 ) g;
  22. -- Results
  23. generate_series
  24. 100
  25. 110
  26. 120
  27. 130
  28. 140
  29. 150
  30. 160
  31. 170
  32. 180
  33. 190
  34. 200
  35. -- Negative decrement
  36. SELECT g.IntValue AS generate_series
  37.   FROM generate_series(5,1,-2) g;
  38. -- Results
  39. generate_series
  40. 5
  41. 3
  42. 1
  43. -- Invalid test
  44. SELECT g.IntValue AS generate_series
  45.  FROM generate_series(4,3,1) g;
  46. -- Results
  47. generate_series
  48. -- Increment negative numbers
  49. SELECT g.IntValue AS generate_series
  50.   FROM generate_series(-4,-1,1) g;
  51. -- Results
  52. generate_series
  53. -4
  54. -3
  55. -2
  56. -1
  57. -- generate some dates
  58. SELECT CONVERT(VARCHAR(20),GETDATE() + sa.IntValue,112) AS dates
  59.   FROM generate_series(0,14,7) sa;
  60. -- Results
  61. dates
  62. 20120410
  63. 20120417
  64. 20120424
  65. -- Create some points
  66. SELECT f.id,
  67.        geometry::Point(f.x,f.y,0 /* SRID */ ).STAsText()  AS geom
  68.   FROM ( SELECT sa.IntValue AS id,
  69.                 ROUND(10000 * RAND(CHECKSUM(NEWID())) +  353880,2) AS x,
  70.                 ROUND(5000  * RAND(CHECKSUM(NEWID())) + 5404973,2) AS y
  71.            FROM dbo.generate_series(1,25,1) sa
  72.         ) f
  73. ORDER BY 1 ASC;
  74. -- Results
  75. id  geom
  76. 1 POINT (363011.9 5406135.94)
  77. 2 POINT (361741 5408272.44)
  78. 3 POINT (363844.43 5408793.59)
  79. 4 POINT (356034.42 5405077.86)
  80. 5 POINT (360968.83 5408948.45)
  81. 6 POINT (363247.97 5408120.85)
  82. 7 POINT (363265.25 5409078.93)
  83. 8 POINT (355839.57 5405431.12)
  84. 9 POINT (358031.78 5408748.88)
  85. 10  POINT (362166.17 5408519.15)
  86. 11  POINT (357931.48 5405419.99)
  87. 12  POINT (362586.12 5404990.02)
  88. 13  POINT (359782.46 5405622.41)
  89. 14  POINT (354394.21 5406409.27)
  90. 15  POINT (355763.87 5406505.26)
  91. 16  POINT (357572.38 5407954.41)
  92. 17  POINT (356033.02 5408066.5)
  93. 18  POINT (360874.83 5407605.39)
  94. 19  POINT (360484.8 5406577.3)
  95. 20  POINT (359978.63 5404987.73)
  96. 21  POINT (363641.33 5407022.35)
  97. 22  POINT (357245.02 5407018.61)
  98. 23  POINT (355047.11 5407032.75)
  99. 24  POINT (357383.37 5405070.77)
  100. 25  POINT (356912.68 5408711.83)
  101. -- Extract Points from a geometry
  102. SELECT sa.IntValue AS pointN,
  103.        a.geom.STPointN(sa.IntValue).STX AS x,
  104.        a.geom.STPointN(sa.IntValue).STY AS y
  105.   FROM (SELECT geometry::STGeomFromText('LINESTRING(0 0,1 0,1 1,2 1,2 2)',0) AS geom) a
  106.        CROSS apply
  107.        dbo.generate_series(1,a.geom.STNumPoints(),1) sa;
  108. -- Results
  109. pointN  x y
  110. 1 0 0
  111. 2 1 0
  112. 3 1 1
  113. 4 2 1
  114. 5 2 2

I hope this function is useful to someone.

Creative Commons License

post this at del.icio.uspost this at Diggpost this at Technoratipost this at Redditpost this at Farkpost this at Yahoo! my webpost this at Windows Livepost this at Google Bookmarkspost this to Twitter

Comment [4]

Simon,

Finally got a chance to look at this but haven’t taken it thru paces yet. It seems your editor is stripping the @
sign. The above function didn’t compile for me until I changed all the variables to have @ in front of them.

Regina · 20 November 2008, 18:36 · #

Regina,

Thanks for pointing out the lack of @ symbols. Yes, Textile was removing them: I have fixed this so all should now be well.

Simon

Simon · 20 November 2008, 22:22 · #

Hi Simon,

The above function looks promising, but I get syntax errors in SSMS – specifically, line 10, syntax error near ‘-=’

Is this line correct? ABS

Cheers,
Kevin

Kevin · 17 July 2009, 18:51 · #

Kevin,

Thanks for pointing out the problem which crept in because of Textpattern formatting. Now fixed. Thanks
Simon

Simon · 18 July 2009, 00:09 · #