SQL 服务器序列与持久计算列?哪个性能更好?

SQL Server Sequence vs Persisted Computed Column? Which one is better for performance?

如果你必须生成唯一的序列号如T1000T10001T10002 ...等等。

想到的两种方法是:

  1. 持久计算列
  2. 用户自定义序列

使用一个比另一个有性能优势吗?

我刚刚比较了 IDENTITY 与 SEQUENCE 的性能。我发现 IDENTITY 的性能稍好一些,因为它的 IO 较少且 CPU.

性能测试设置

CREATE TABLE #test_Identity
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
NAME CHAR(1) NOT NULL,
TID AS CONCAT('T',ID) PERSISTED)

CREATE SEQUENCE dbo.SEQ_VAL Start with 1 increment by 1;

CREATE TABLE #test_seq
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
NAME CHAR(1) NOT NULL DEFAULT 'A',
TID CHAR(10) NOT NULL)

SET STATISTICS IO ON
SET STATISTICS TIME ON

性能测试:插入 10000 行。

  • 使用序列
    INSERT INTO #test_seq(TID)
    SELECT CONCAT('T',NEXT VALUE FOR dbo.SEQ_VAL)
    FROM (SELECT TOP 10000 * FROM sys.objects) AS T

SQL Server parse and compile time:     CPU time = 14 ms, elapsed time
    = 14 ms. 
Table '#test_seq_____00000000569F'. Scan count 0, logical reads 21418, physical reads 0, 
read-ahead reads 30,lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 

Table 'sysschobjs'. Scan count 1, logical reads 242, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:    CPU time = 141 ms,  elapsed time = 247 ms.

  • 使用身份
    INSERT INTO #test_Identity(Name)
    SELECT top 10000 'A'
    FROM sys.objects

SQL Server parse and compile time:     CPU time = 13 ms, elapsed time
    = 13 ms. 
Table '#test_______________00000000569D'. Scan count 0, logical reads 21413, physical reads 0, 
read-ahead reads 31, lob logical reads 0, lob physical reads 0, 
lob read-ahead reads 0. Table 'sysschobjs'. Scan count 1, logical reads 242, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:    CPU time = 110 ms,  elapsed time = 101 ms.