2020年5月23日 星期六

SQLServer隔離層級RCSI和SI的比較

https://github.com/imrexhuang/SQLServerIsolation-RCSIvsSI/

  • SQL Server預設的隔離層級是RC(Read Committed)
  • 使用Row Version Base的隔離層級,要好好管理TempDB並最佳化、大型交易分批做
  • 使用RCSI要注意副作用(特別是和金額有關),最好不要在舊系統使用,新系統上線前可以完整測試比較安全
  • SQL Server 2005之後支援RSCI(Read Committed Snapshot Isolation)和SI(Snapshot Isolation)的隔離層級,但這兩種層級不支援分散式交易

GROUP BY無法使用alias column name

原因
https://stackoverflow.com/questions/3841295/sql-using-alias-in-group-by

SQL is implemented as if a query was executed in the following order:
  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause
For most relational database systems, this order explains which names (columns or aliases) are valid because they must have been introduced in a previous step.
So in Oracle and SQL Server, you cannot use a term in the GROUP BY clause that you define in the SELECT clause because the GROUP BY is executed before the SELECT clause.
There are exceptions though: MySQL and Postgres seem to have additional smartness that allows it.

問題描述:
SELECT country AS c, YEAR(hiredate) AS yearhired, COUNT(*) AS numemployees
FROM HR.Employees
WHERE hiredate >= '20140101'
GROUP BY country, YEAR(hiredate)
-- GROUP BY country, yearhired -- 無效的資料行名稱 'yearhired'。
HAVING COUNT(*) > 1
ORDER BY country, yearhired DESC;
--ORDER BY c, yearhired DESC; --可以執行