Search code examples
sqlms-accessadditionexistsalter

MS Access: adding column if not exist (or try/catch it)


this is an easy question, but I can't find out the solution...

I have to check if a column exists and add it if the test is negative. How can I do with only sql code?

This is the syntax for SQL Server:

IF NOT EXISTS (
  SELECT * 
  FROM   sys.columns 
  WHERE  object_id = OBJECT_ID(N'[dbo].[Person]') 
         AND name = 'ColumnName'
)
BEGIN
    --STUFF HERE
END

and for MS Access, using only SQL code... what is the right syntax to do it?

UPDATE: also a way to do a try cath statement would be ok, I only need to not add anything if it doesn't exist... so, also a try catch is ok, I think. Also try catch is easily possible to use in sql server... and for access?

UPDATE 2: I have done this:

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

    ALTER TABLE TabTessereVeicoli ADD TAGA text(25) NULL;

end

but I get the error "SQL statement not valid. Expected DELETE, INSERT, PROCEDURE, SELECT or UPDATE." Why? How can I do an alter table after an IF?


Solution

  • You can't do this in Access SQL. You can either run this:

    ALTER TABLE TabTessereVeicoli ADD TAGA text(25) NULL;
    

    and just ignore an error, or you can use VBA to open the TableDef and do your modifications.