如何使用动态更新游标

时间:2018-03-19 07:37:25

标签: sql sql-server sql-update

我需要按照这个规则对数据进行编码:根据当前单词的长度,我改变单词的字母并在同一个表中更新,我不知道在这种情况下如何使用UPDATE游标,很想得到榜样。 这是我目前的代码:

DECLARE @name varchar(30)       
DECLARE currentCursor  CURSOR for select Lastname from contact;
OPEN  currentCursor
FETCH NEXT FROM currentCursor INTO @name                    
            Declare @Length int =0;     
            Declare @newName varchar(30)
            select @Length =   LEN(@name);  
             --     DECLARE currentCursor2  CURSOR for update
            while @Length >0
                begin
                    set @newName = concat( @newName,  CHAR(CAST(27 * RAND() + 224 AS INT)) )
                    set @Length = @Length -1;                                                           
               end
            --  FETCH NEXT FROM currentCursor2 INTO @newName  
                update contact 
                set LastName = @newName
                where lastname = @name
CLOSE currentCursor;
DEALLOCATE currentCursor

1 个答案:

答案 0 :(得分:0)

您遇到的问题与您使用的光标类型无关,主要问题是您使用的游标语法不正确。即使您使用更新游标,也会遇到相同的问题。

可以在此处找到游标的官方文档:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

第一个问题是因为你只进行一次提取,你需要不断提取,直到你到达结果集的末尾。

第二个问题是你没有在迭代之间重置新名称

SQL的更新版本在

之下
DECLARE @name varchar(30)       
DECLARE currentCursor  CURSOR for select Lastname from contact;
OPEN  currentCursor
FETCH NEXT FROM currentCursor INTO @name   

WHILE @@FETCH_STATUS = 0 -- While the last fetch was successful
BEGIN
    DECLARE @Length int = 0;     
    DECLARE @newName varchar(30) = '' -- reset new name
    SELECT @Length = LEN(@name);  

    WHILE @Length > 0
    BEGIN
        SET @newName = concat( @newName,  CHAR(CAST(27 * RAND() + 224 AS INT)) )
        SET @Length = @Length -1;                                                           
    END

    UPDATE contact 
    SET    LastName = @newName
    WHERE  lastname = @name

    -- Fetch the next row
    FETCH NEXT FROM currentCursor INTO @name   
END
CLOSE currentCursor;
DEALLOCATE currentCursor