使用内部联接更新到相同的表优化

时间:2009-02-19 11:41:46

标签: sql-server

查询是:

CREATE TABLE logfile (
   sequence_number BIGINT,
   start_time DECIMAL,
   finish_time DECIMAL,
   irp_major VARCHAR(100),
   offset BIGINT,
   length BIGINT,
   filename VARCHAR(2000),
   is_seq BIT 
   );
//bulk insert 120 000 rows
CREATE CLUSTERED INDEX IX_logfile ON logfile(sequence_number); 
UPDATE dbo.logfile SET is_seq = (
SELECT  CASE WHEN a.offset = (b.offset + b.length) THEN 1 ELSE 0 END AS seq
FROM    dbo.logfile a
        LEFT JOIN dbo.logfile b
            ON a.sequence_number = b.sequence_number + 1
WHERE a.sequence_number = logfile.sequence_number)

无论如何我可以提高更新查询的性能吗?

2 个答案:

答案 0 :(得分:1)

MERGE
INTO logfile l
USING (
  SELECT sequence_number + 1 AS pseq,
         p.*
  FROM logfile p
) pl
ON l.sequence_number = pseq
WHEN MATCHED THEN
  UPDATE
  SET is_seq = CASE WHEN l.offset = (pl.offset + pl.length) THEN 1 ELSE 0 END

答案 1 :(得分:1)

也许这次更新会更快

UPDATE dbo.LogFile SET is_seq = 0
UPDATE dbo.LogFile SET is_seq = 1
FROM dbo.LogFile f
     INNER JOIN (
       SELECT f2.sequence_number
       FROM dbo.LogFile f1
            INNER JOIN dbo.LogFile f2 ON f2.sequence_number = f1.sequence_number + 1     
       WHERE f1.Offset <> f2.Offset + f2.Length
     ) f2 ON f2.sequence_number = f.sequence_number