我建立使用光標作爲@AllRecords將值插入臨時表&然後獲取從該臨時表值的SQL查詢。但是當我從表中獲取值時(錯誤:@AllRecords附近的錯誤語法),它在最後一條語句中顯示錯誤。下面是我的代碼:
DECLARE @ColName varchar(20)=null,
@Query varchar(MAX)=null,
@DepartmentName varchar(50)=null,
@deptt_code varchar(4)=null,
@DistrictId varchar(4)='0001',
@Deptt_Id char(4)=null,
@stYear varchar(4)=null,
@cYear varchar(4)=null,
@yr varchar(9)='2017-2018',
@tno int
BEGIN
set @stYear = SUBSTRING(@yr,0,5)
set @cYear = SUBSTRING(@yr,6,4)
--DECLARE & SET COUNTER
DECLARE @counter int
SET @counter = 1
--CREATE DYNAMIC TABLE WITH COLs
DECLARE @AllRecords table
(
department_name varchar(50),
project_name varchar(100),
department_code varchar(4)
)
--*** Declare Cursor
DECLARE cur_FetchDepartmentName CURSOR READ_ONLY
FOR
select deptt_code,deptt_name+'('+ RTRIM(LTRIM(deptt_short))+')' as dept_name from m_Department
where deptt_code in (select distinct department_code from t_Project_Details where [email protected]
and [email protected])
OPEN cur_FetchDepartmetName
fetch next from cur_FetchDepartmetName into
@deptt_code, @DepartmentName
--LOOP UNTIL RECORDS ARE AVAILABLE
while @@FETCH_STATUS=0
BEGIN
if(@tno=0)
BEGIN
set @tno=1
insert into @AllRecords values(@DepartmentName,@deptt_code)
fetch next from cur_FetchDepartmetName into
@deptt_code,@DepartmentName
END
else
BEGIN
set @[email protected]+1
insert into @AllRecords values(@DepartmentName,@deptt_code)
fetch next from cur_FetchDepartmetName into
@deptt_code,@DepartmentName
END
END
--CLOSE CURSOR
CLOSE cur_FetchDepartmetName
DEALLOCATE cur_FetchDepartmetName
select department_name, department_code from @AllRecords
當你設置你的第一個變量,你必須' BEGIN'沒有關聯的'END' – HoneyBadger
這必須是不必要地使用遊標的最好例子。請停下來,喘口氣,並將其重寫爲一個簡單的INSERT..SELECT語句。我會說要使用ROW_NUMBER()或IDENTITY()來獲得@tNo,但我沒有看到任何意義,你不再使用它們了? –