細微之處看看mysql與sql server的一些差別

以前不怎麼使用mysql,最近有些事情,需要用到php和mysql。目前使用的版本是5.5.1

發現mysql與sql server有很多不同。可能逐漸地會整理一些文檔出來給大家參考。

 

今天第一篇說說,update操作的差異。在mysql中,如果update語句要設置的新值,與數據庫中當前的值是一樣的,其實意味着無需更改。這種操作是不會被執行的。

為什麼會發現這個問題呢?因為我在php程序中,需要獲取update語句所影響的行數。我發現很多時候為0. 追查下去,才明白他是這樣做的。從下圖中可以看到,我執行update語句兩次,第一次是修改了數據的(Changed:1),而第二次則沒有修改(Changed:0)。

image

而查閱php的幫助文檔,也很清楚地定義了這個行為

http://php.net/manual/en/function.mysql-affected-rows.php

Returns the number of affected rows on success, and -1 if the last query failed.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility thatmysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.

 

同樣的語句,在sql server中就不是這樣。例如下面這樣,其實兩個語句是一模一樣的,但每個都會被執行,一行被更改

image

為了證明這一點,我可以寫一個觸發器來檢測一下

CREATE TRIGGER TestTrigger
ON employees
FOR UPDATE

AS
BEGIN
    DECLARE @id INT
    DECLARE @name NVARCHAR(50)
    
    SELECT @id=UID,@name=Name FROM DELETED
    PRINT @id
    PRINT @name

END

再次執行語句,我們可以看到如下結果

image

這說明什麼問題?說明sql server的update語句確實每次都會執行,不管值是否有必要進行變化。

在sql server中,update操作會有兩個步驟,首先執行delete操作,然後執行insert操作。

上面的觸發器代碼中,訪問的deleted表,是一個邏輯表,裡面保存的就是delete的數據,也就是我們經常所說的“舊值”

posted @ 2011-04-24 14:42  陈希章  阅读(2606)  评论(9编辑  收藏  举报