2
我遇到隨機結束的cursur問題。我想爲每個元素生成一行,因此對於每個元素,2012年的每個月都會有一行。如果某個特定月份缺少一行,它也應該創建該行。現在遊標永不在T-SQL中結束
,它產生於每月的最後一個元素的行,直到一年2057
現在,我對每個元素的行,直到每月,直到一年2057只爲我的表中的一個元素。
我的表設計:
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')
我的代碼:
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 @@[email protected]@month+1
end
close tmepTbl
Deallocate tmepTbl
我現在表
cName cRemarks Date
name1 Text1 2012-01-01
name2 Text2 2012-01-01
我想follwing發生:
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
等。
謝謝!
Thx!我會將光標轉換爲此 – Knaks