Set MySQL delimiter inside an sql-file - mysql

I want to set the delimiter inside an sql file (because I cannot rely on users to do that through the terminal).
Is there a mysql statement that will allow me to set the delimiter?
Using
DELIMITER //
throws an error.
# Categories schema
# --- !Ups
CREATE TABLE IF NOT EXISTS `category` (
`id` INT NOT NULL AUTO_INCREMENT ,
`pid` INT NULL DEFAULT 0 ,
`label` VARCHAR(64) NULL ,
`active` TINYINT NULL DEFAULT 0,
PRIMARY KEY (`id`) );
DELIMITER //
CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INT
NOT DETERMINISTIC
READS SQL DATA
BEGIN
DECLARE _id INT;
DECLARE _parent INT;
DECLARE _next INT;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET #id = NULL;
SET _parent = #id;
SET _id = -1;
IF #id IS NULL THEN
RETURN NULL;
END IF;
LOOP
SELECT MIN(id)
INTO #id
FROM category
WHERE pid = _parent
AND id > _id;
IF #id IS NOT NULL OR _parent = #start_with THEN
SET #level = #level + 1;
RETURN #id;
END IF;
SET #level := #level - 1;
SELECT id, pid
INTO _id, _parent
FROM category
WHERE id = _parent;
END LOOP;
END//
DELIMITER ;
# --- !Downs
#DROP TABLE category;
We got the following error: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near 'DELIMITER / CREATE FUNCTION
hierarchy_connect_by_parent_eq_prior_id(value INT) ' at line 1
[ERROR:1064, SQLSTATE:42000], while trying to run this SQL script:

In the version of MySql I use the same error occurs when using the delimiter command, but this version handles the delimiter ";" for statements and delimiter "|" for stored procedures and functions, which i think solves the problem; try this:
-- any comma-terminated statements here (select, create table, drop table, update, delete, etc)
CREATE FUNCTION hierarchy_connect_by_parent_eq_prior_id(value INT) RETURNS INT
-- function body here
END
|
-- other statements or functions here

Change delimiter in sql file as below:
-- # delimeter=/
-- # delimeter=;

Related

syntax error : 1064 , when creating a stored procedure

CREATE table parent_user
( userid int auto_increment PRIMARY KEY,
Username varchar(100) NOT NULL,
Password varchar(200) NOT NULL,
Email varchar(200) NOT NULL
);
EDIT : OK so I made some changes:
CREATE PROCEDURE `parent_reg` (
pUserName varchar(100)
pPassword varchar(200)
pEmail varchar(200)
)
as
Begin
Declare Count int
Declare ReturnCode int
Select Count = Count(Username)
from parent_user where Username = #Username
If Count > 0
Begin
Set ReturnCode = -1
End
Else
Begin
Set ReturnCode = 1
insert into parent_user values
(pUserName, pPassword, pEmail)
End
Select pReturnCode as ReturnValue
End
But I still got the same error-
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'pPassword varchar(200) pEmail varchar(200) ) ....'
The syntax error is at 'pPassword varchar(200)'
The code in the question is invalid syntax for MySQL Stored Procedure. It looks more like Microsoft SQL Server (Transact SQL) syntax.
Some observations:
MySQL procedure variables cannot start with # because that character is reserved for user-defined variables.
MySQL doesn't use a NVARCHAR type. The setting of the character_set_client variable in the session (at the time the procedure is created) is what controls the characterset of the procedure variables.
The line select * from parent_user, before the CREATE PROCEDURE looks entirely out of place.
Missing semicolons (statement terminators).
The INSERT is for a table with four columns; there are only three values and no column list.
If the goal is to create a stored procedure in MySQL, we'd need syntax closer to this:
DELIMITER $$
CREATE PROCEDURE parent_reg(p_username VARCHAR(100),
p_password VARCHAR(200), p_email VARCHAR(200)
)
BEGIN
DECLARE mycount INT;
DECLARE myreturncode INT;
SELECT COUNT(pu.username)
INTO mycount
FROM `parent_user` pu
WHERE pu.username = p_username;
IF (mycount > 0 ) THEN
SET myreturncode = -1;
ELSE
SET myreturncode = 1;
INSERT INTO `parent_user` (`username`, `password`, `email`)
VALUES (p_username, p_password, p_email);
END IF;
SELECT myreturncode AS `ReturnValue`;
END$$
DELIMITER ;
Maybe it's your database's collation. When installing SQL Server and choose your default collation, there's a "case sensitivity" checkbox. Certain collations are case sensitive and will affect your queries (and stored procedures).
A lot of vendors don't test their products on servers with case sensitive collations, which leads to runtime errors.
So just try to choose between "Username" and "UserName"

Set the value of a variable to the result from a SELECT statement in MySQL

I want to create the following function in Mysql, but the function does not get created but fails with an error
DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT)
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
DECLARE #AccountType varchar(50);
SELECT AccountType INTO #AccountType
FROM AccountType
WHERE AccountTypeID = AccountTypeID);
RETURN AccountType;
END $$
DELIMITER ;
A description of my table
CREATE TABLE AccountType(
AccountTypeID INT AUTO_INCREMENT PRIMARY KEY,
AccountType varchar(100) UNIQUE NOT NULL
);
The error I am getting is
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '#AccountType varchar(50);
I can't seem to find out what I am doing wrong. Can someone please help.
This should work:
DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT)
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
SELECT AccountType INTO #AccountType FROM AccountType
WHERE AccountTypeID = AccountTypeID;
RETURN #AccountType;
END $$
DELIMITER ;
This will also work:
DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT)
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
DECLARE v_AccountType varchar(50) DEFAULT NULL;
SELECT AccountType INTO v_AccountType FROM AccountType
WHERE AccountTypeID = AccountTypeID;
RETURN v_AccountType;
END $$
DELIMITER ;
The first example uses a "global" variable (those starting with an '#' symbol). The second example uses a "local" variable.

Creating mysql Function with parameters

delimeter //
DROP function IF EXISTS get_seq_next//
create function get_seq_next(
IN sequence_ref_ varchar(30)
) returns int(11) unsigned
BEGIN
DECLARE seq_val_ int(11) unsigned;
LOCK TABLE ga_seq_tab WRITE;
select sequence_no into seq_val_ from ga_seq_tab where sequence_ref=sequence_ref_;
if not seq_val_ is null then
update ga_seq_tab set sequence_no=sequence_no+1 where sequence_ref=sequence_ref_;
end if
UNLOCK TABLES;
return seq_val;
END //
DELIMETER ;
I'm trying to create a function but it keeps saying I have syntax errors and I am not sure what is wrong with it
Try removing the IN reserved word in the parameters list.

Warning 1072 in MySql - Key column 'name' doesn't exist in table`

Getting the warning 0 row(s) affected, 1 warning(s):
1072 Key column 'name' doesn't exist in table And I do not know what it means. Does anybody have an explaination?
The table/SP is as follows
CREATE TABLE IF NOT EXISTS `sectors`
(
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`sector` VARCHAR(25) NOT NULL ,
--
PRIMARY KEY (`id`) ,
UNIQUE INDEX `sector_idx` USING BTREE (`sector` ASC)
);
DELIMITER $$
CREATE PROCEDURE `AddSector` (IN sector VARCHAR(25),
OUT result BOOLEAN)
MODIFIES SQL DATA
BEGIN
DECLARE CONTINUE HANDLER FOR SQLWARNING, SQLEXCEPTION SET result = FALSE;
SET result = TRUE;
--
INSERT INTO `sectors` (`sector`) VALUES (sector);
COMMIT;
END $$
Change the procedure to:
DELIMITER $$
CREATE PROCEDURE `AddSector` (IN pSector VARCHAR(25), <<-- fix nameclash here
OUT result BOOLEAN)
MODIFIES SQL DATA
BEGIN
DECLARE CONTINUE HANDLER FOR SQLWARNING, SQLEXCEPTION SET result = FALSE;
SET result = TRUE;
INSERT INTO `sectors` (`sector`) VALUES (pSector); <<-- and here
-- COMMIT; <<-- You don't need a commit.
END $$
All stuff inside a stored proc is already run inside an implicit transaction, so the commit is not needed, and may actually be an error (not sure).
DELIMITER ;

Using a check contraint in MySQL for controlling string length

I'm tumbled with a problem!
I've set up my first check constraint using MySQL, but unfortunately I'm having a problem. When inserting a row that should fail the test, the row is inserted anyway.
The structure:
CREATE TABLE user (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
uname VARCHAR(10) NOT NULL,
fname VARCHAR(50) NOT NULL,
lname VARCHAR(50) NOT NULL,
mail VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
CHECK (LENGTH(fname) > 30)
);
The insert statement:
INSERT INTO user VALUES (null, 'user', 'Fname', 'Lname', 'mail#me.now');
The length of the string in the fname column should be too short, but it's inserted anyway.
I'm pretty sure I'm missing something basic here.
MySQL doesn't enforce CHECK constraints, on any engine.
Which leads me to ask, why would you declare the fname column as VARCHAR(50), but want to enforce that it can only be 30 characters long?
That said, the only alternative is to use a trigger:
CREATE TRIGGER t1 BEFORE INSERT ON user
FOR EACH ROW BEGIN
DECLARE numLength INT;
SET numLength = (SELECT LENGTH(NEW.fname));
IF (numLength > 30) THEN
SET NEW.col = 1/0;
END IF;
END;
As mentioned above you have to use a trigger, MySQL doesn't support check, also when you have multiple statements inside your trigger block, like declaring variables or control flows, you need to start it with begin and end and enclose your trigger inside two delimiters:
Note: If you use MariaDB use // after the first delimiter and before the second delimiter, otherwise if you use MySQL use $$ instead.
delimiter //
create trigger `user_insert_trigger` before insert on `user` for each row
begin
declare maximumFnameLength int unsigned;
declare fNameLength int unsigned;
set maximumFnameLength = 30;
set fNameLength = (select length(new.fNameLength));
if (fNameLength > maximumFnameLength) then
signal sqlstate '45000'
set message_text = 'First name is more than 30 characters long.';
end if;
end
//
delimiter ;