Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 For/ While loop

Author  Topic 

Corne
Starting Member

1 Post

Posted - 2015-02-19 : 03:31:34
I want to, for each month of the year 2014 say, to create a loop that will enter data into a table.

Right now I have:

Select [Member Number],
sum(case when [Receipt Date]='2014/01/01' then Amount else 0 end) as [Rec 2014/01/01]
From [Receipts Table]
Group by [Member Number]
Insert into [Receipts 2014/01/01]

Select [Member Number],
sum(case when [Receipt Date]='2014/02/01' then Amount else 0 end) as [Rec 2014/02/01]
From [Receipts Table]
Group by [Member Number]
Insert into [Receipts 2014/02/01]

Instead I would just like to do something like…
Declare i date
For i=2014/01/01 to 2014/12/01

Select [Member Number],
sum(case when [Receipt Date]=i then Amount else 0 end) as [Rec +i]

From [Receipts Table]
Group by [Member Number]
Insert into [Receipts + i]

Don’t know if this is at all possible?

pradeepbliss
Starting Member

28 Posts

Posted - 2015-02-19 : 06:59:35
Create Procedure [dbo].[SP_TestDateInsert](@Fromdate date,@Todate date)
as
begin
declare @i date
set @i = @FromDate
while @i <= @ToDate
begin
--Insert statement
set @i= dateadd(day,30,@i)
print @i
end
end

Exec [SP_TestDateInsert] '2014/01/01','2014/10/01'
Go to Top of Page

gbritton
Master Smack Fu Yak Hacker

2780 Posts

Posted - 2015-02-19 : 08:54:18
Not sure why you want to write a loop in SQL. That way leads to the dark side.
Go to Top of Page
   

- Advertisement -