2011-01-06 185 views

回答

3

可以使用Information_schema觀點:

If Not Exists (Select Column_Name 
       From INFORMATION_SCHEMA.COLUMNS 
       Where Table_Name = 'YourTable' 
       And Column_Name = 'YourColumn') 
begin 

-- Column doesn't exist 

end 

此外,您可能希望通過包括數據庫和/或模式進一步限制where條款。

If Not Exists (Select Column_Name 
       From INFORMATION_SCHEMA.COLUMNS 
       Where Table_Name = 'YourTable' 
       And Column_Name = 'YourColumn' 
       And Table_Catalog = 'YourDatabaseName' 
       And Table_Schema = 'YourSchemaName') 

begin 

-- Column doesn't exist 

end 
+0

我收到錯誤「SQL指令無效,請執行DELETE,INSERT,PROCEDURE,SELECT或UPDATE」。爲什麼? – 2015-04-03 08:31:59

2
if Exists(select * from sys.columns where Name = N'columnName' 
      and Object_ID = Object_ID(N'tableName')) 

begin 

    -- Column Exists 

end 

"REFERENCE"

+0

這隻適用於SQL Server - 不清楚OP正在使用哪個數據庫... – 2011-01-06 08:47:44

2
IF NOT EXISTS (SELECT 1 
FROM syscolumns sc 
JOIN sysobjects so 
ON sc.id = so.id 
WHERE so.Name = 'TableName' 
AND sc.Name = 'ColumnName') 
BEGIN 
--- do your stuff 
END