将存储过程/游标更改为更新表

时间:2016-12-09 01:27:55

标签: sql mysqli

我有以下存储过程:

CREATE PROC FilmLength
AS
BEGIN
DECLARE @Name CHAR(40) ,@Minutes INT
DECLARE Filmcursor  CURSOR 
       FOR (SELECT FilmName, FilmRunTimeMinutes from tblFilm)

OPEN filmcursor
FETCH NEXT  FROM filmcursor  INTO  @Name, @Minutes
WHILE (@@FETCH_STATUS = 0)
BEGIN
    IF @Minutes < 120           PRINT (@Name + 'is a SHORT film')
    ELSE IF @Minutes <150   PRINT (@Name + 'is a MEDIUM Length film')
    ELSE                            PRINT (@Name + 'is a LONG film')
    FETCH NEXT  FROM filmcursor   INTO  @Name, @Minutes
END
CLOSE filmcursor
DEALLOCATE filmcursor
END

我需要它来更新并将短,中,长标签添加到名为Duration的同一个表中的列中,而不是打印。我已经尝试将PRINT更改为SET但它没有通过。

这就是我正在使用的,但它没有经历过。我正在使用

Use Movies
Execute FilmLength
Select *
from tblFilm

执行

USE Movies
GO
ALTER PROC FilmLength
AS
BEGIN
DECLARE @Minutes INT, @Duration Char(6)
DECLARE Filmcursor  CURSOR 
       FOR (SELECT FilmRunTimeMinutes, Duration from tblFilm)

OPEN filmcursor
FETCH NEXT  FROM filmcursor  INTO  @Name, @Minutes
WHILE (@@FETCH_STATUS = 0)
BEGIN
    IF @Minutes < 120           SET @Duration = 'SHORT'
    ELSE IF @Minutes <150       SET @Duration = 'MEDIUM'
    ELSE                        SET @Duration = 'LONG'
    FETCH NEXT  FROM filmcursor   INTO  @Name, @Minutes
END
CLOSE filmcursor
DEALLOCATE filmcursor
END

1 个答案:

答案 0 :(得分:0)

好的,根据你告诉我的关于你的桌子及其专栏的内容,你不需要光标(他们不赞成),这可以做得很多使用简单的更新/案例陈述更容易。

USE movies 

UPDATE tblfilm 
SET    duration = ( CASE 
                      WHEN ( filmruntime < 120 ) THEN 'SHORT' 
                      WHEN ( filmruntime BETWEEN 120 AND 150 ) THEN 'MEDIUM' 
                      ELSE 'LONG' 
                    END ) 

SELECT * 
FROM   tblfilm 

希望这就是你所需要的。我假设您的表格列如下。

FilmName VARCHAR(MAX)
FilmRunTime数字(18,0)
持续时间VARCHAR(MAX)

如果你的列数据类型不同,请告诉我。