【发布时间】:2017-09-25 07:29:47
【问题描述】:
先生,
我已经构建了一个 SQL 查询,使用 Cursor 作为 @AllRecords 将值插入临时表,然后从该临时表中获取值。但是当我从表中获取值时,它在最后一条语句中显示错误(错误:@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 district_id=@DistrictId
and financial_year=@yr)
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 @tno=@tno+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 -
这必须是不必要使用游标的最好例子。请停下来,深呼吸,然后将其重写为一个简单的 INSERT..SELECT 语句。我会说使用 ROW_NUMBER() 或 IDENTITY() 来获取 @tNo,但我认为没有意义,你不再使用它们了吗?
标签: sql sql-server-2008 cursor