4

How do I check if a column exists in a table using a SQL query? I'm using Access 2007.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
Hossein Moradinia
  • 6,116
  • 14
  • 59
  • 85

3 Answers3

3

You can use the Information_schema views:

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

-- Column doesn't exist

end

In addition, you may want to restrict the where clause further by including the Database and/or schema.

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
codingbadger
  • 42,678
  • 13
  • 95
  • 110
  • I get the error "SQL instruction not valid. Expeted DELETE, INSERT, PROCEDURE, SELECT or UPDATE". Why? – Piero Alberto Apr 03 '15 at 08:31
  • There is no INFORMATION_SCHEMA in MS Access. This is not a valid answer. INFORMATION_SCHEMA exists in MS SQL Server. – Aris Aug 05 '19 at 20:25
2
if Exists(select * from sys.columns where Name = N'columnName'  
            and Object_ID = Object_ID(N'tableName'))

begin

    -- Column Exists

end

"REFERENCE"

Community
  • 1
  • 1
VoodooChild
  • 9,776
  • 8
  • 66
  • 99
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
Anil Soman
  • 2,443
  • 7
  • 40
  • 64