In SQL, is UPDATE always faster than DELETE+INSERT?

前端 未结 15 2183
梦谈多话
梦谈多话 2020-11-29 20:01

Say I have a simple table that has the following fields:

  1. ID: int, autoincremental (identity), primary key
  2. Name: varchar(50), unique, has unique index<
15条回答
  •  一生所求
    2020-11-29 20:50

    One command on the same row should always be faster than two on that same row. So the UPDATE only would be better.

    EDIT set up the table:

    create table YourTable
    (YourName  varchar(50)  primary key
    ,Tag int
    )
    
    insert into YourTable values ('first value',1)
    

    run this, which takes 1 second on my system (sql server 2005):

    SET NOCOUNT ON
    declare @x int
    declare @y int
    select @x=0,@y=0
    UPDATE YourTable set YourName='new name'
    while @x<10000
    begin
        Set @x=@x+1
        update YourTable set YourName='new name' where YourName='new name'
        SET @y=@y+@@ROWCOUNT
    end
    print @y
    

    run this, which took 2 seconds on my system:

    SET NOCOUNT ON
    declare @x int
    declare @y int
    select @x=0,@y=0
    while @x<10000
    begin
        Set @x=@x+1
        DELETE YourTable WHERE YourName='new name'
        insert into YourTable values ('new name',1)
        SET @y=@y+@@ROWCOUNT
    end
    print @y
    

提交回复
热议问题