I have problems with a cursur that’s ends randomly. I want to produce a row for each element , so for every element there is a row for every month in 2012. If there is a row missing for a specific month, it should create that as well.
Now, it’s producing a row for the last element in every month until year 2057.
Now, I have a row for each element until in every month until year 2057 and only for one element in my table.
My table design:
create table tblDataUpdateTest
(
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),
[Date] date,
)
insert into tblDataUpdateTest (cName, cRemarks,[Date]) values ('name1','Text1','2012-01-01'),
('name2','Text2','2012-01-01')
My code:
declare @y as int
declare @d as int
SET @y = 2012
SET @d = 1
Declare @@counter int
Declare @@month int
set @@counter=0
Declare @@slno int
Declare @@cRemarks varchar(100)
Declare @@cName varchar(50)
Declare @@Date date
set @@month = 1
Declare tmepTbl cursor
For
Select slno,cName,cRemarks,date from tblDataUpdateTest
Open tmepTbl /* Opening the cursor */
fetch next from tmepTbl
into @@slno,@@cName,@@cRemarks,@@Date
while @@fetch_Status=-1
begin
if not exists (select cRemarks from tblDataUpdateTest where MONTH(Date) = @@month AND YEAR(Date) = 2012)
begin
insert into tblDataUpdateTest (cName, cRemarks,[Date]) values (@@cName,'s',(DateAdd(yy, 2012-1900,DateAdd(m, @@month - 1, 01 - 1))))
end
fetch next from tmepTbl
into @@slno,@@cName,@@cRemarks,@@Date
set @@month=@@month+1
end
close tmepTbl
Deallocate tmepTbl
My table now
cName cRemarks Date
name1 Text1 2012-01-01
name2 Text2 2012-01-01
I want follwing to happen:
cName cRemarks Date
name1 Text1 2012-01-01
name1 Text1 2012-02-01
name1 Text1 2012-03-01
name2 Text2 2012-01-01
name2 Text2 2012-02-01
name2 Text2 2012-03-01
and so on.
Thanks!
Wouldn’t be better to use a recursive CTE, instead of a cursor?
Here is an example: