2011-01-06 126 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