問題描述
我正在嘗試編寫一個更新列的 DML 腳本,但我想確保該列首先存在,因此我將其包裝在 IF EXISTS 塊中
I'm trying to write a DML script that updates a column but I wanted to make sure the column existed first so I wrapped it in a IF EXISTS block
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Client' AND COLUMN_NAME='IsClarityEnabled')
BEGIN
UPDATE Client SET IsClarityEnabled = 1 WHERE ClientID = 21
END
所以奇怪的是,即使它沒有滿足條件,它也會嘗試執行更新.所以列不存在并且 UPDATE 語句運行并且我收到一個錯誤.為什么?
So the weirdness is that it tries to execute the update even if it fails the condition. So column doesn't exist and the UPDATE statement runs and I get an error. Why?
更奇怪的是,這確實有效:
Even stranger is that this does work:
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Client' AND COLUMN_NAME='IsClarityEnabled')
BEGIN
EXEC('UPDATE Client SET IsClarityEnabled = 1 WHERE ClientID = 21')
END
UPDATE 命令是否有什么特別之處導致其行為如此?
Is there something special about an UPDATE command that causes it to behave this way?
推薦答案
問題是腳本會被編譯/解析,如果該列不存在,就會出現編譯/解析錯誤.
The problem is that the script will be compiled/parsed, and if the column does not exist, you will have a compile/parse error.
無效的列名'IsClarityEnabled'.
Invalid column name 'IsClarityEnabled'.
這篇關于包含在 IF EXISTS 塊中的 UPDATE 語句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!