不多說,直接看例子吧
USE [AdventureWorks2012];
IF OBJECT_ID('dbo.T1', 'U') IS NOT NULL DROP TABLE dbo.T1;
GO
CREATE TABLE dbo.T1
(
col1 INT NULL,
col2 VARCHAR(10) NOT NULL
);
INSERT INTO dbo.T1(col2)
VALUES('A'),('B'),('C'),('D'),('E'),('F');
怎麼依col2排序編col1流水號呢?
以前我會這樣,用參考CTE的,然後Update目標資料表T1
WITH CTE AS
(
SELECT
col2,
ROW_NUMBER() OVER(ORDER BY col2) AS ROWNUM
FROM dbo.T1
)
UPDATE T1
SET col1 = ROWNUM
WITH CTE AS
(
SELECT
col1,
col2,
ROW_NUMBER() OVER(ORDER BY col2) AS ROWNUM
FROM dbo.T1
)
UPDATE CTE
SET col1 = ROWNUM;
來比較兩個執行計畫的成本,如下圖,用Join CTE的要68%,而不Join直接Update CTE的只要32%,優劣立判,可以直接Update CTE是不是很方便呀!
0 意見:
張貼留言