If Exists 语句不起作用

Jam*_*mes 2 sql sql-server-2012

我在 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
Run Code Online (Sandbox Code Playgroud)

我也试过下面

if exists(select * from sys.columns 
      where Name = 'Age' and Object_ID = Object_ID('Table1'))
Run Code Online (Sandbox Code Playgroud)

执行这两个语句都会出错 Invalid column name Age

不明白为什么它会进入Begin块内。

Gor*_*off 5

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;
Run Code Online (Sandbox Code Playgroud)