SQL Server FOR EACH Loop

0 votes

SQL query:

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

Returns : '1/1/2010'.

I want to create a calendar with dates like: 

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

  SELECT @MyVar

So this would return:-

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

I may need to add some sort of union at the conclusion of the query so that each iteration of the loop unions onto the next because I want this to provide the data as a single resultset rather than numerous resultsets. 

Aug 18, 2022 in Database by Kithuzzz
• 38,000 points
4,990 views

No answer to this question. Be the first to respond.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.

Related Questions In Database

0 votes
1 answer

Syntax of for-loop in SQL Server

TSQL has no for-loop, we have only ...READ MORE

answered Feb 15, 2022 in Database by Neha
• 9,020 points
910 views
0 votes
0 answers

Which SQL server should we use for SQL queries to be executed?

I mean to say which SQL server ...READ MORE

Aug 18, 2019 in Database by Sonali
533 views
0 votes
1 answer

SQL Server replaces LEFT JOIN for LEFT OUTER JOIN in view query

You are getting the joins confused and ...READ MORE

answered Feb 4, 2022 in Database by Neha
• 9,020 points
1,481 views
0 votes
1 answer

How to do version control for SQL Server database?

Not only can you compare objects at ...READ MORE

answered Feb 15, 2022 in Database by Neha
• 9,020 points
637 views
0 votes
0 answers

How Stuff and 'For Xml Path' work in SQL Server?

Table is: Id Firstname 4 abc 4 def 4 ghi 4 jkl 4 mno Required output: Id Name 4 abc,def,ghi,jkl,mno Query: SELECT ID, ...READ MORE

Feb 23, 2022 in Database by Neha
• 9,020 points
5,978 views
0 votes
1 answer

How do I UPDATE from a SELECT in SQL Server?

MERGE INTO YourTable T USING ...READ MORE

answered Feb 3, 2022 in Database by Vaani
• 7,070 points
819 views
0 votes
0 answers

How do I UPDATE from a SELECT in SQL Server?

INSERT INTO Table (col1, col2, col3) SELECT col1, ...READ MORE

Feb 4, 2022 in Database by Vaani
• 7,070 points
545 views
0 votes
1 answer

What is a stored procedure?

A stored procedure is a set of ...READ MORE

answered Feb 4, 2022 in Database by Neha
• 9,020 points
1,053 views
0 votes
1 answer

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

At the top level there are mainly ...READ MORE

answered Feb 4, 2022 in Database by Neha
• 9,020 points
1,987 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP