SQL Server上的语法错误

时间:2011-03-30 19:22:21

标签: sql sql-server-2000

这可能是一个愚蠢的语法错误,但我只是继续阅读我的程序,但我无法弄清楚我的错误在哪里。

  

Msg 156,Level 15,State 1,Line 41
  关键字附近的语法不正确   'FOR'。

这是我的代码:

alter procedure LockReservation as
DECLARE @edition_id tinyint, @stockid  tinyint;
DECLARE @creservation CURSOR FOR select edition_id from reservation where (date_fin - GETUTCDATE()) <= 12;
open creservation;
while @@fetch_status = 0
BEGIN
    fetch creservation into @edition_id;
    DECLARE @cstock CURSOR 
        FOR select id from stock where edition_id = @edition_id;
    open cstock;
    while @@fetch_status = 0
    BEGIN
        fetch cstock into @stockid;
        select stock_id from location where location.stock_id = @stockid and archivage = 0
        if @@rowcount = 0
        BEGIN
             insert into stocks_reserves(id, date_ajout, usure, suppression, edition_id) 
                    Select id, date_ajout, usure, suppression, edition_id 
                from stock 
                where stock.id = @stockid
        END
    END
    CLOSE cstock
    DEALLOCATE cstock
END
CLOSE creservation
DEALLOCATE creservation

有人能帮助我吗?

4 个答案:

答案 0 :(得分:13)

请勿在光标名称中使用@符号。

答案 1 :(得分:3)

摆脱光标 - 使用基于集合的解决方案。

基本上你这样做:

insert into stocks_reserves
(id, date_ajout, usure, suppression, edition_id) 
Select id, date_ajout, usure, suppression, edition_id 
from stock 
where stock.id in
(
    select stock_id 
    from location 
    where location.stock_id in
    (
        select id 
        from stock 
        where edition_id in
        (
            select edition_id 
            from reservation 
            where (date_fin - GETUTCDATE()) <= 12
        )
    )
    and archivage = 0
)

您可以使用exists替换IN以更快地处理插入。

更好的是,INNER JOIN可能表现最佳。

答案 2 :(得分:1)

将游标名称命名为@creservation

答案 3 :(得分:1)

@语句

中删除游标名称前的DECLARE @cstock CURSOR符号