簡體   English   中英

If Exists 語句不起作用

[英]If Exists statement not working

我在 Sql server 2012 上執行下面的語句。但它總是執行,即使列不存在

IF  EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table1' AND COLUMN_NAME = 'Age')
begin
  Print 'in'
  Update Table1 set Age = Null

End

我也試過下面

if exists(select * from sys.columns 
      where Name = 'Age' and Object_ID = Object_ID('Table1'))

執行這兩個語句會出現錯誤Invalid column name Age

不明白為什么它會進入Begin塊。

exists語句正在起作用。 問題是update 您的代碼在if運行之前被編譯。 因此,錯誤發生在編譯階段。

您可以使用動態 SQL 解決此問題:

IF EXISTS (SELECT *
           FROM INFORMATION_SCHEMA.COLUMNS
           WHERE TABLE_NAME = 'Table1' AND COLUMN_NAME = 'Age')
begin
  Print 'in'
  exec sp_executesql N'Update Table1 set Age = Null';
End;

執行時,SQL 服務器嘗試編譯存儲過程,但未能成功。 應用一點動態 sql 將解決您的問題:

IF  EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Table1' AND COLUMN_NAME = 'Age')
begin
  Print 'in'
  EXEC sp_executesql 'Update Table1 set Age = Null'
End

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM