Skip to content
Snippets Groups Projects
gtDBUpdateColumn.m 1.88 KiB
function gtDBUpdateColumn(table_name,pattern,expression)
% GTDBUPDATECOLUMN  Access a column in a table to be updated in an
%                   expression
%
%     gtDBUpdateColumn(table_name,field_name,expression)
%     --------------------------------------------------
%     INPUT:
%       table_name = name of the table in the database <string>
%       pattern    = variable or pattern name; can be part of the varialbe
%                    name; i.e. 'CentroidY' or 'Y' <string>
%       expression = Expression to be applied to all the values in the
%                    column(s) given by pattern. Use '_var_' as the variable name 
%                    i.e. expression = '_var_ = _var_ + 1' <string>

% show columns for the table
[fields_list,~,~,~,~,~] = mym(['SHOW COLUMNS FROM ' table_name]);

% get fields corresponding to pattern
[mod_fields,~,~,~,~,~] = mym(['SHOW COLUMNS FROM ' table_name ' WHERE FIELD LIKE "%' pattern '%"']);



% prepare expression to be applied to each column
mym_expr=cell(size(mod_fields));
if ~isempty(mod_fields)
    for ii = 1:length(mod_fields)
        mym_expr{ii}=strrep(expression, '_var_', mod_fields{ii});
        check = inputwdefault(['Is the expression correct: ' mym_expr{ii} ' ? [y/n]'], 'y');
        if strcmpi(check,'n')
            mym_expr{ii} = input('Insert the right expression (between single quotes) [''_var_'' can be used]: ');
            mym_expr{ii} = strrep(mym_expr{ii},'_var_',mod_fields{ii});
        end
    end
    
    
    disp(['Expressions to be applied for the table ' table_name])
    disp(mym_expr)
    
    for ii = 1:length(mod_fields)
        check = inputwdefault(['Do you want to apply this expression: ' mym_expr{ii} ' ? [y/n]'], 'y');
        if strcmpi(check,'y')
            mym(['UPDATE ' table_name ' SET ' mym_expr{ii}]);
            disp(['Updated ' table_name ' : ' mym_expr{ii}]);
        end 
    end

end


end % end of function