T-SQL游标不产生预期的输出

时间:2010-07-22 12:00:12

标签: tsql

GO
SET NOCOUNT ON;

DECLARE
@idAdvertisements int,
@Name nvarchar(255),
@Description nvarchar(500),
@DepartureDate datetime,
@Cities_idCities int,
@Areas_idAreas int,
@Countries_idCountries int,
@Agencies_idAgencies int,
@Url nvarchar(1000),
@Price decimal(6, 2),
@HollidayDuration int,
@BookingDate datetime;

DECLARE ad_cursor CURSOR
   FOR SELECT idAdvertisements
             ,Name
             ,Description
             ,DepartureDate
             ,Cities_idCities
             ,Areas_idAreas
             ,Countries_idCountries
             ,Agencies_idAgencies
             ,Url
             ,Price
             ,HollidayDuration
             ,BookingDate
      FROM Advertisements;

OPEN ad_cursor;
FETCH NEXT FROM ad_cursor
INTO @idAdvertisements
    ,@Name
    ,@Description
    ,@DepartureDate
    ,@Cities_idCities
    ,@Areas_idAreas
    ,@Countries_idCountries
    ,@Agencies_idAgencies
    ,@Url
    ,@Price
    ,@HollidayDuration
    ,@BookingDate;

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT ' ';
   PRINT @idAdvertisements;
   --PRINT @Name;
   --PRINT @Description;
   --PRINT @DepartureDate;
   --PRINT @Cities_idCities;

END
CLOSE ad_cursor; 

但我总是得到1, 1, 1, 1, 1。数据总是一样的。

SELECT声明没问题。我不明白为什么。有人能看到问题吗?

3 个答案:

答案 0 :(得分:3)

这里的代码将无限循环。您需要在FETCH循环正文的末尾添加另一个WHILE,否则@@FETCH_STATUS将永远不会更改。

答案 1 :(得分:3)

游标是邪恶的... eVIL .. eVil .. 远离他们

现在,问题出在这里 - 你没有向前移动光标..

DECLARE ad_cursor CURSOR
   FOR SELECT idAdvertisements, Name, Description, DepartureDate, Cities_idCities, Areas_idAreas,
    Countries_idCountries, Agencies_idAgencies, Url, Price, HollidayDuration, BookingDate FROM Advertisements;

OPEN ad_cursor;
FETCH NEXT FROM ad_cursor
INTO @idAdvertisements, @Name, @Description, @DepartureDate, @Cities_idCities, @Areas_idAreas,
@Countries_idCountries, @Agencies_idAgencies, @Url, @Price, @HollidayDuration, @BookingDate;

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT ' ';
   PRINT @idAdvertisements;
   --PRINT @Name;
   --PRINT @Description;
   --PRINT @DepartureDate;
   --PRINT @Cities_idCities;

    FETCH NEXT FROM ad_cursor
    INTO @idAdvertisements, @Name, @Description, @DepartureDate, @Cities_idCities, @Areas_idAreas,
    @Countries_idCountries, @Agencies_idAgencies, @Url, @Price, @HollidayDuration, @BookingDate;


END
CLOSE ad_cursor; 

答案 2 :(得分:2)

OPEN ad_cursor;
FETCH NEXT FROM ad_cursor
INTO @idAdvertisements, @Name, @Description, @DepartureDate, @Cities_idCities, @Areas_idAreas,
@Countries_idCountries, @Agencies_idAgencies, @Url, @Price, @HollidayDuration, @BookingDate;

WHILE @@FETCH_STATUS = 0
BEGIN
   PRINT ' ';
   PRINT @idAdvertisements;
   --PRINT @Name;
   --PRINT @Description;
   --PRINT @DepartureDate;
   --PRINT @Cities_idCities;
FETCH NEXT FROM ad_cursor
INTO @idAdvertisements, @Name, @Description, @DepartureDate, @Cities_idCities, @Areas_idAreas,
@Countries_idCountries, @Agencies_idAgencies, @Url, @Price, @HollidayDuration, @BookingDate;
END
CLOSE ad_cursor; 

您已在END

之前添加了获取下一行的内容