<p>How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.<p>
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
<p>For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:</p>

<pre><code>select sum(n) from numbers where n between 100 and 200
</code></pre>

<p>Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.</p>

<p>[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. <a href="https://stackoverflow.com/questions/58429/sql-set-based-range#59657">See below.</a></p>

[{'answer_id': 58511, 'author': 'Sergio Acosta', 'author_id': 2954, 'author_profile': 'https://Stackoverflow.com/users/2954', 'pm_score': 0, 'selected': False, 'text': '<p>If using SQL Server 2000 or greater, you could use the <strong>table datatype</strong> to avoid creating a normal or temporary table. Then use the normal table operations on it.</p>\n\n<p>With this solution you have essentially a table structure in memory that you can use almost like a real table, but much more performant.</p>\n\n<p>I found a good discussion here: <a href="http://www.odetocode.com/articles/365.aspx" rel="nofollow noreferrer">Temporary tables vs the table data type</a></p>\n'}, {'answer_id': 59188, 'author': 'Anders Eurenius', 'author_id': 1421, 'author_profile': 'https://Stackoverflow.com/users/1421', 'pm_score': 1, 'selected': False, 'text': '<p>This is basically one of those things that reveal SQL to be less than ideal. I\'m thinking maybe the right way to do this is to build a function that creates the range. (Or a generator.)</p>\n\n<p>I believe the correct answer to your question is basically, "you can\'t".\n(Sorry.)</p>\n'}, {'answer_id': 59314, 'author': 'Chris Ammerman', 'author_id': 2729, 'author_profile': 'https://Stackoverflow.com/users/2729', 'pm_score': 4, 'selected': True, 'text': '<p>I think the very short answer to your question is to use WITH clauses to generate your own.</p>\n\n<p>Unfortunately, the big names in databases don\'t have built-in queryable number-range pseudo-tables.  Or, more generally, easy pure-SQL data generation features.  Personally, I think this is a <strong>huge</strong> failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.</p>\n\n<p>So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.</p>\n\n<p>Oracle and T-SQL both support a WITH clause that can be used to do this.  They work a little differently in the different DBMS\'s, and MS calls them "common table expressions", but they are very similar in form.  Using these with recursion, you can generate a sequence of numbers or text values fairly easily.  Here is what it might look like...</p>\n\n<p>In Oracle SQL:</p>\n\n<pre><code>WITH\n  digits AS  -- Limit recursion by just using it for digits.\n    (SELECT\n      LEVEL - 1 AS num\n    FROM\n      DUAL\n    WHERE\n      LEVEL &lt; 10\n    CONNECT BY\n      num = (PRIOR num) + 1),\n  numrange AS\n    (SELECT\n      ones.num\n        + (tens.num * 10)\n        + (hundreds.num * 100)\n        AS num\n    FROM\n      digits ones\n      CROSS JOIN\n        digits tens\n      CROSS JOIN\n        digits hundreds\n    WHERE\n      hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.\nSELECT\n  -- Some columns and operations\nFROM\n  numrange\n  -- Join to other data if needed\n</code></pre>\n\n<p>This is admittedly quite verbose.  Oracle\'s recursion functionality is limited.  The syntax is clunky, it\'s not performant, and it is limited to 500 (I think) nested levels.  This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.</p>\n\n<p>I haven\'t used SQL Server\'s Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle.  Whether performance is comparable, and what the nesting limits are, I don\'t know.</p>\n\n<p>At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets.  Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data.  Aggregations, duplications, combinations, permutations, and so on.  You can even use such generated data to aid in rolling up or drilling down into other data.</p>\n\n<p><strong>UPDATE:</strong> I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL.  It\'s not just a scripting language.  It\'s a fairly robust data-driven <a href="http://en.wikipedia.org/wiki/Declarative_programming_language" rel="nofollow noreferrer">declarative language</a>.  Sometimes it\'s a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations.  But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.</p>\n'}, {'answer_id': 59657, 'author': 'Hafthor', 'author_id': 4489, 'author_profile': 'https://Stackoverflow.com/users/4489', 'pm_score': 2, 'selected': False, 'text': '<p>I created a SQL CLR table valued function that works great for this purpose.</p>\n\n<pre><code>SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11\nSELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this)\n</code></pre>\n\n<p>Here\'s the code:</p>\n\n<pre><code>using System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Collections;\n\n[assembly: CLSCompliant(true)]\nnamespace Range {\n    public static partial class UserDefinedFunctions {\n        [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRow", TableDefinition = "n bigint")]\n        public static IEnumerable Range(SqlInt64 start, SqlInt64 end, SqlInt64 incr) {\n            return new Ranger(start.Value, end.Value, incr.Value);\n        }\n\n        [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRowF", TableDefinition = "n float")]\n        public static IEnumerable RangeF(SqlDouble start, SqlDouble end, SqlDouble incr) {\n            return new RangerF(start.Value, end.Value, incr.Value);\n        }\n\n        public static void FillRow(object row, out SqlInt64 n) {\n            n =  new SqlInt64((long)row);\n        }\n\n        public static void FillRowF(object row, out SqlDouble n) {\n            n = new SqlDouble((double)row);\n        }\n    }\n\n    internal class Ranger : IEnumerable {\n        Int64 _start, _end, _incr;\n\n        public Ranger(Int64 start, Int64 end, Int64 incr) {\n            _start = start; _end = end; _incr = incr;\n        }\n\n        public IEnumerator GetEnumerator() {\n            return new RangerEnum(_start, _end, _incr);\n        }\n    }\n\n    internal class RangerF : IEnumerable {\n        double _start, _end, _incr;\n\n        public RangerF(double start, double end, double incr) {\n            _start = start; _end = end; _incr = incr;\n        }\n\n        public IEnumerator GetEnumerator() {\n            return new RangerFEnum(_start, _end, _incr);\n        }\n    }\n\n    internal class RangerEnum : IEnumerator {\n        Int64 _cur, _start, _end, _incr;\n        bool hasFetched = false;\n\n        public RangerEnum(Int64 start, Int64 end, Int64 incr) {\n            _start = _cur = start; _end = end; _incr = incr;\n            if ((_start &lt; _end ^ _incr &gt; 0) || _incr == 0)\n                throw new ArgumentException("Will never reach end!");\n        }\n\n        public long Current {\n            get { hasFetched = true; return _cur; }\n        }\n\n        object IEnumerator.Current {\n            get { hasFetched = true; return _cur; }\n        }\n\n        public bool MoveNext() {\n            if (hasFetched) _cur += _incr;\n            return (_cur &gt; _end ^ _incr &gt; 0);\n        }\n\n        public void Reset() {\n            _cur = _start; hasFetched = false;\n        }\n    }\n\n    internal class RangerFEnum : IEnumerator {\n        double _cur, _start, _end, _incr;\n        bool hasFetched = false;\n\n        public RangerFEnum(double start, double end, double incr) {\n            _start = _cur = start; _end = end; _incr = incr;\n            if ((_start &lt; _end ^ _incr &gt; 0) || _incr == 0)\n                throw new ArgumentException("Will never reach end!");\n        }\n\n        public double Current {\n            get { hasFetched = true; return _cur; }\n        }\n\n        object IEnumerator.Current {\n            get { hasFetched = true; return _cur; }\n        }\n\n        public bool MoveNext() {\n            if (hasFetched) _cur += _incr;\n            return (_cur &gt; _end ^ _incr &gt; 0);\n        }\n\n        public void Reset() {\n            _cur = _start; hasFetched = false;\n        }\n    }\n}\n</code></pre>\n\n<p>and I deployed it like this:</p>\n\n<pre><code>create assembly Range from \'Range.dll\' with permission_set=safe -- mod path to point to actual dll location on disk.\ngo\ncreate function dbo.Range(@start bigint, @end bigint, @incr bigint)\n  returns table(n bigint)\n  as external name [Range].[Range.UserDefinedFunctions].[Range]\ngo\ncreate function dbo.RangeF(@start float, @end float, @incr float)\n  returns table(n float)\n  as external name [Range].[Range.UserDefinedFunctions].[RangeF]\ngo\n</code></pre>\n'}, {'answer_id': 153973, 'author': 'ilitirit', 'author_id': 9825, 'author_profile': 'https://Stackoverflow.com/users/9825', 'pm_score': 0, 'selected': False, 'text': "<p>Here's a hack you should never use:</p>\n\n<pre><code>select sum(numberGenerator.rank)\nfrom\n(\nselect\n    rank =  ( select count(*)  \n              from reallyLargeTable t1 \n              where t1.uniqueValue &gt; t2.uniqueValue ), \n    t2.uniqueValue id1, \n    t2.uniqueValue id2\nfrom reallyLargeTable t2 \n) numberGenerator\nwhere rank between 1 and 10\n</code></pre>\n\n<p>You can simplify this using the Rank() or Row_Number functions in SQL 2005</p>\n"}, {'answer_id': 7556043, 'author': 'Mike Powell', 'author_id': 205, 'author_profile': 'https://Stackoverflow.com/users/205', 'pm_score': 1, 'selected': False, 'text': '<p>You can use a common table expression to do this in SQL2005+.</p>\n\n<pre><code>WITH CTE AS\n(\n    SELECT 100 AS n\n    UNION ALL\n    SELECT n + 1 AS n FROM CTE WHERE n + 1 &lt;= 200\n)\nSELECT n FROM CTE\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/58429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4489/']