You are on page 1of 6

sign up log in tour help

Questions

stack overflow careers

Tags

Users

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no
registration required.

Badges

search

Unanswered

Ask Question

Take the 2-minute tour

SQL Server FOR EACH Loop


asked 2 years ago
viewed 160085 times
active

1 month ago

I have the following SQL query:Blog

16

DECLARE @MyVar datetime = '1/1/2010'


SELECT @MyVar

JNat and animuson: workin


on ur problemz

This naturally returns '1/1/2010'.


5

What i want to do is have a list of dates, say:1/1/2010


2/1/2010
3/1/2010
4/1/2010
5/1/2010

Then i want to FOR EACH through the numbers and run the SQL Query.
Something like (pseudocode):List = 1/1/2010,2/1/2010,3/1/2010,4/1/2010,5/1/2010
For each x in List
do
DECLARE @MyVar datetime = x

Linked
2 transfer data from one table

SELECT @MyVar

to another in sql server

So this would return:-

1 how to do a FOR EACH

loop in T-Sql using join?

1/1/2010 2/1/2010 3/1/2010 4/1/2010 5/1/2010


I want this to return the data as one resultset, not multiple resultsets, so I may need to use some kind
of union at the end of the query, so each iteration of the loop unions onto the next.

Related
497 How to perform an IF

THEN in an SQL SELECT?

edit

1069 Add a column, with a

I have a large query that accepts a 'to date' parameter, I need to run it 24 times, each time with a
specific to date which I need to be able to supply (these dates are going to be dynamic) I want to avoid
repeating my query 24 times with union alls joining them as if I need to come back and add additional
columns it would be very time consuming.
sql

sql-server

default value, to an existing


table in SQL Server

473 How to return the date part

only from a SQL Server


datetime datatype

215 Hidden Features of SQL

tsql

Server

share improve this question

edited Apr 24 '12 at 14:58

asked Apr 24 '12 at 14:49


SelectDistinct
2,031

36

77

421 Check if table exists in SQL

Server

474 Left join and Left outer join

in SQL Server

385 How can I do an UPDATE

statement with JOIN in


SQL?

237 SQL Server: How to Join to

first row

1229 UPDATE from SELECT

using SQL Server

2 SQL Server sample of each


type of record

converted by W eb2PDFConvert.com

5 Can you explain why you need to do this? 95% of the time when you need a looping structure in tSQL you
are probably doing it wrong. JohnFx Apr 24 '12 at 14:53
2 Why not create a table where you can populate the dates you want to run it against that. There is almost
certainly a better way to do this than looking through hardcoded constant values. JohnFx Apr 24 '12 at
14:57

Hot Network Questions


Using a cheap table saw
How to portably find out
min(INT_MAX, abs(INT_MIN))?

The dates in your example are sequential by month. Is that a rule, or do you need to be able to run for an
arbitrary set of dates? Is there a reason that you can't edit the large query to take a date range or set of dates
rather than a single date? If you absolutely need to step through iterations (against the good advice given
above), then you might want to consider using a cursor. Jason Quinones Apr 24 '12 at 22:36

Changing the email address linked


to my Steam account
MVVM data binding for a video
encoding form
Is there any way to see how Google
ranks my websites 'mobile
friendliness'?
Does A5 have a subgroup of order
6?
Is cleveref safe to use?

6 Answers

active

oldest

votes

What do you call the act of


searching something by walking?
"mv file" and now it's missing

SQL is primarily a set-orientated language - it's generally a bad idea to use a loop in it.

23

Is it possible to "read" secure (using


SSL or TLS) messages if you know
the message?

In this case, a similar result could be achieved using a recursive CTE:

Nicolas Cage film where there are


multiples of himself appearing from
him

with cte as
(select 1 i union all
select i+1 i from cte where i < 5)
select dateadd(d, i-1, '2010-01-01') from cte

Grep first 50 lines of files for pattern


Telescopic Parentheses

share improve this answer

edited Apr 24 '12 at 15:02

answered Apr 24 '12 at 14:57


Mark Bannister
31.4k

15

42

Ordering of the commands used to


install from a ppa
Word for 'possessing large gravity
well'?
Including follow up salary
information in a thank you email?
How to remove dust after sanding
before applying paint/oil/glue?
Is there still a use for inline?
Hudson Bay Falling Sea Level
What is the difference between find .
and find . -print
How can I ensure my dll has not
been modified?
How can I automatically replace all
accentuated characters by the
corresponding codes in
TeXnicCenter?
Why don't things get destroyed by
gas molecules flying around?
Leibniz golf in C#

converted by W eb2PDFConvert.com

Here is an option with a table variable:

19

DECLARE @MyVar TABLE(Val DATETIME)


DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'
WHILE @I <= 5
BEGIN
INSERT INTO @MyVar(Val)
VALUES(@StartDate)
SET @StartDate = DATEADD(DAY,1,@StartDate)
SET @I = @I + 1
END
SELECT *
FROM @MyVar

You can do the same with a temp table:


CREATE TABLE #MyVar(Val DATETIME)
DECLARE @I INT, @StartDate DATETIME
SET @I = 1
SET @StartDate = '20100101'
WHILE @I <= 5
BEGIN
INSERT INTO #MyVar(Val)
VALUES(@StartDate)
SET @StartDate = DATEADD(DAY,1,@StartDate)
SET @I = @I + 1
END
SELECT *
FROM #MyVar

You should tell us what is your main goal, as was said by @JohnFx, this could probably be done
another (more efficient) way.
share improve this answer

edited Apr 24 '12 at 15:22

answered Apr 24 '12 at 14:54


Lamak
36.8k

38

59

I need to loop dates not integers, see edited question. Would a WHILE loop work with dates ?
SelectDistinct Apr 24 '12 at 15:12
@SelectDistinct - Yes, it should work just fine. I changed my answer to returns dates instead of ints
Lamak Apr 24 '12 at 15:22
1 Mark Bannister's answer is less code and more efficient. There's no reason to use a while loop for something
like this. Sorpigal Apr 24 '12 at 16:41

This kind of depends on what you want to do with the results. If you're just after the numbers, a setbased option would be a numbers table - which comes in handy for all sorts of things.

For MSSQL 2005+, you can use a recursive CTE to generate a numbers table inline:
;WITH Numbers (N) AS (
SELECT 1 UNION ALL
SELECT 1 + N FROM Numbers WHERE N < 500
)
SELECT N FROM Numbers
OPTION (MAXRECURSION 500)

share improve this answer

answered Apr 24 '12 at 14:57


Mark Brackett
52.5k

69

116

converted by W eb2PDFConvert.com

Interesting that you consider this to be a "set-based option" (the word RECURSION is a bit of a give away!)
onedaywhen Apr 25 '12 at 8:17
@onedaywhen - there's no contradiction there. A recursive CTE is set-based. The anchor member (SELECT 1)
is set S[0], which is then UNION ALL'ed with n more sets (SELECT 1 + N FROM S[n - 1]) until an empty set
is encountered. The result is the UNION of sets S[0] to S[n]. That being said - I personally prefer a physical
table as it's more efficient. Mark Brackett Apr 25 '12 at 13:52
Joe Celko's thoughts on the matter: "it makes the semi-procedural programmer feel good to use [a recursive]
CTE... But recursion is actually a procedural technique. It is also expensive since it is really a cursor under
the covers" -- I'm not saying he is correct but demonstrates the position isn't as clear cut as you would have it.
Not a criticism of your comments either. As I said, I find it interesting without holding strong views on the
subject myself :) onedaywhen Apr 26 '12 at 7:26
@onedaywhen - And here, Celko makes a distinction between "procedural code...a procedure or a cursor" and
a recursive CTE, which "[is] still procedural under the covers". I don't doubt that recursive CTEs are
procedurally executed...but so are JOINs. At least we can agree that a numbers table is a better option.
Mark Brackett Apr 26 '12 at 14:43

declare @counter as int


set @counter = 0
declare @date as varchar(50)
set @date = cast(1+@counter as varchar)+'/01/2013'
while(@counter < 12)
begin
select cast(1+@counter as varchar)+'/01/2013' as date
set @counter = @counter + 1
end

share improve this answer

edited Sep 6 '13 at 18:40


Jamie Kitson
1,076

13

29

answered Jul 12 '13 at 16:22


younes
41

You could use a variable table, like this:

declare @num int


set @num = 1
declare @results table ( val int )
while (@num < 6)
begin
insert into @results ( val ) values ( @num )
set @num = @num + 1
end
select val from @results

share improve this answer

edited Feb 16 at 21:46


guneysus
821

13

answered Apr 24 '12 at 14:55


Steve Mayne
9,611

19

33

+1 this worked well. Bob Blogge May 22 '13 at 14:58

converted by W eb2PDFConvert.com

[CREATE PROCEDURE [rat].[GetYear]

AS
BEGIN
-- variable for storing start date
Declare @StartYear as int
-- Variable for the End date
Declare @EndYear as int
-- Setting the value in strat Date
select @StartYear = Value from rat.Configuration where Name = 'REPORT_START_YEAR';
-- Setting the End date
select @EndYear = Value from

rat.Configuration where Name = 'REPORT_END_YEAR';

-- Creating Tem table


with [Years] as
(
--Selecting the Year
select @StartYear [Year]
--doing Union
union all
-- doing the loop in Years table
select Year+1 Year from [Years] where Year < @EndYear
)
--Selecting the Year table
selec]

share improve this answer

edited Mar 19 at 12:39


Soner Gnl
47k

18

88

answered Mar 19 at 12:20


user3702431
152

29

Your Answer

Sign up or log in
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange

Post as a guest
Name

Email
required, but never shown

converted by W eb2PDFConvert.com

Post Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged sql
question.

sql-server

tsql

or ask your own

question feed

tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback

TECHNOLOGY
Stack Overflow

Programmers

Server Fault

Unix & Linux

Super User

Ask Different (Apple)

Web Applications
Ask Ubuntu

WordPress
Development

Webmasters

Geographic
Information Systems

Game Development

Electrical Engineering

TeX - LaTeX

Android Enthusiasts
Information Security

Database
Administrators

LIFE / ARTS

CULTURE /
RECREATION

SCIENCE

OTHER

Photography

English Language &


Usage

Mathematics

Stack Apps

Cross Validated (stats)

Meta Stack Exchange


Area 51

Drupal Answers

Science Fiction &


Fantasy

SharePoint

Graphic Design

Mi Yodeya (Judaism)

Theoretical Computer
Science

User Experience

Seasoned Advice
(cooking)

Travel

Physics

Christianity

MathOverflow

Arqade (gaming)

more (7)

Mathematica
Salesforce
more (14)

Home Improvement
Personal Finance &
Money

Bicycles

Academia

Role-playing Games

more (10)

more (21)

site design / logo 2015 stack exchange inc; user contributions licensed under cc by-sa 3.0 with attribution required
rev 2015.4.22.2509

Skeptics

Stack Overflow Careers

You might also like