Reputation: 43
I am using MySQL database with C# to develop an application.Using MySQL Server 5.0 and odbc connector.
In some cases I am required to execute ddl commands such as ALTER TABLE
or CREATE TABLE
to manipulate the database. In these cases I need to use the IF EXISTS
command to check the database before I execute commands. I write below commands that execute without any problem in Navicat or Workbench, but do not work when send this commands with application by ExecuteNoneQury
methods.
what is wrong?
use db;
drop procedure if exists sp_update ;
delimiter //
create procedure sp_update()
begin
if not exists( SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tab' AND COLUMN_NAME = 'col' and table_schema = 'db') then
ALTER TABLE `tab` ADD COLUMN `col` int(11) NULL DEFAULT NULL ;
end if;
end//
delimiter ;
call sp_update();
drop procedure if exists sp_update ;
C# Command :
public override int ExecuteNoneQuery(string commandText)
{
int obTemp = 0;
Conn = new MySqlConnection(Connection.ConnectionString);
try
{
MySqlCommand MySqlCommand = new MySqlCommand(commandText, Conn);
if (Conn.State == ConnectionState.Closed)
{
Conn.Open();
}
obTemp = MySqlCommand.ExecuteNonQuery();
}
finally
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
return obTemp;
}
Upvotes: 3
Views: 1554
Reputation: 43
I solved my own problem. I needed to split up my sql command into two parts.
Part 1 create procedure:
drop procedure if exists sp_update ;
create procedure sp_update()
begin
if not exists( SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tab' AND COLUMN_NAME = 'col' and table_schema = 'db') then
ALTER TABLE `tab` ADD COLUMN `col` int(11) NULL DEFAULT NULL ;
end if;
end
Part 2:
call sp_update();
drop procedure if exists sp_update ;
Send each command to MySQL separately.
Upvotes: 1
Reputation: 5653
"delimiter" is not MySQL syntax.. It is a convinience function for the mysql command line client and is only understood by it (well, some GUI clients mimic the behavior too, to be able to run scripts that are originally thought for command line client).
But, you do not need "delimiter" in any code executed by connectors. Using it will result in syntax error like the one you got.
Upvotes: 3