首先使用While循环读取id更新表

时间:2014-07-30 18:35:35

标签: sql-server while-loop sql-update

我只是想问一些问题,我想更新一个表,但是这个表有300k行,每行需要大约1.8 - 2.3秒这是我需要更新的表,如果名称与我需要的列匹配设置列All的值 ID |cexp_cod |All |name |New |Normal |Vip 1 |13 |9 |Vip |NULL |NULL |NULL 2 |16 |9 |Vip |NULL |NULL |NULL 3 |16 |6 |Normal |NULL |NULL |NULL 4 |18 |9 |Vip |NULL |NULL |NULL 5 |23 |9 |New |NULL |NULL |NULL 6 |25 |9 |New |NULL |NULL |NULL 7 |26 |9 |Vip |NULL |NULL |NULL 8 |27 |9 |New |NULL |NULL |NULL 9 |40 |9 |Vip |NULL |NULL |NULL 10 |43 |9 |Vip |NULL |NULL |NULL 11 |43 |6 |Normal |NULL |NULL |NULL

这是我的疑问:

 DECLARE @loop      smallint     = 0
,@v_xp_cod      varchar(max) = 0
,@v_name            varchar(MAX) = NULL
,@v_pond        varchar(max) = 0
,@v_id              bigint       = 0

WHILE @loop = 0
    BEGIN

        SELECT TOP 1 @v_xp_cod = query01.xp_cod 
        ,@v_name = query01.name
        ,@v_pond = query01.All
        ,@v_id = query01.ID
        FROM (
            SELECT xp_cod 
            , name
            , All 
            , ID
            FROM temp WITH(NOLOCK)
        ) AS query01
        WHERE query01.ID > @v_id
        ORDER BY query01.ID ASC

        IF @@rowcount=0
        BEGIN
            SET @loop=1
        END

        ELSE -- update
        BEGIN

            DECLARE @i_update nvarchar(MAX)=null
            SELECT @i_update = 'UPDATE temp
                                SET [' +@v_name+ '] = '+@v_pond+'
                                WHERE xp_cod = ' + @v_xp_cod 
            EXECUTE sp_executesql  @i_update

        END         
    END

1 个答案:

答案 0 :(得分:0)

也许尝试使用不同的方法或格式重写查询:

UPDATE MyTable
SET MyColumnName =
( SELECT table2.Name
 FROM table2
 WHERE table2.my_id = MyTable.id)
WHERE EXISTS
   ( SELECT table2.Name
     FROM table2
     WHERE table2.my_id = MyTable.id);