For MS-Access
:
Since you are doing this at application code, you can wrap it in a try .. catch
block. If column exists then it will throw an exception, which you can catch and do whatever needed like
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandText = "alter table [" +tableName + "] add [" + columnName + "] long";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
//do your processing
}
finally
{
con?.Close();
}
If using SQL Server
then
You can check against sys.columns
system view like
SELECT 1 FROM sys.columns
WHERE [name] = N'your_new_columnName'
AND [object_id] = OBJECT_ID(N'Your_tableName');
Again, yo be better you can consider wrapping this in a stored procedure and call that procedure in your application code like
create procedure usp_altertable(table_name varchar(20), column_name varchar(20))
as
begin
DECLARE @sql varchar(100);
IF NOT EXISTS(SELECT 1 FROM sys.columns
WHERE [name] = N'your_new_columnName'
AND [object_id] = OBJECT_ID(N'Your_tableName'))
SET @sql = 'alter table ' +table_name +' add ' + column_name + ' long';
EXEC(@sql);
end
Finally, if table_name
and column_name
are coming as user input from UI then be wary of SQL Injection and use parameterized query instead.