I just keep getting the error 1064. I searched how to do while loops then declare local variables etc. and I don't see what I'm doing wrong. I tried to do it without the ";" and I tired setting the delimiter as "|" to be able to use ";" as a separator between lines (I read something somwhere that kind of said it could be the way to do it?..)
I'm trying to do that query on PhpMyAdmin and my MySql version is 5.1.36
I'm not going to explain what I'm trying as I believe it is easy to understand by simply reading my query below.
BEGIN
DECLARE v1 INT DEFAULT 0;
DECLARE v2 VARCHAR(10);
WHILE v1 < 20 DO
SET v2 = CONCAT('Test ', CAST(v1 AS CHAR(2)));
INSERT INTO news(title,date, message) VALUES(v2, NOW(), v2);
SET v1 = v1 + 1;
END WHILE;
END;
MySql only allows compound statements using the BEGIN...END tag inside stored programs.
From the Docs:
BEGIN ... END syntax is used for
writing compound statements, which can
appear within stored programs
The first thing i can see is a small syntax error within the CAST parameters.
You have:
CAST(v1 ASCHAR(2))
You need:
CAST(v1 AS CHAR(2))
See http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast
Change
DECLAREv2 VARCHAR(10);
to
DECLARE v2 VARCHAR(10);
Related
I'm using HeidiSQL to connect to MySQL 5.7.14
I've researched how to declare a variable, but it's giving me this error. Even when on its on.
Does anyone know what is wrong with this?
Thanks
DECLARE total_sale INT;
Screen Shot Entire SQL
DECLARE is used in programs. As the documentation states:
DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.
You can simply set the value:
SET total_sale = 0;
I'm trying to figure out how to store variables inside a function in mySQL. I am trying to create a function that capitalizes a field name. Creating a function works if I don't create variables. The problem is this is difficult to read, and is easy to make mistakes with.
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
RETURN CONCAT(UPPER(LEFT(string,1)), LOWER(RIGHT(string, LENGTH(string) - 1)));
When I try to add variables using the DECLARE and SET keywords, it no longer works.
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
DECLARE first_letter TEXT;
DECLARE last_letters TEXT;
SET first_letter = UPPER(LEFT(string,1));
SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
RETURN CONCAT(first_letter, last_letters);
I get this error message
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 '' at line 4
I've fiddled around with it, removing semicolons, and double/triple checking parentheses. I've fiddled with BEGIN and END statements but nothing seems to work at all.
I have searched extensively on this topic but cannot figure out where the problem lies.
The body of a CREATE FUNCTION can consist of only a single statement, which is why the first version works and the second doesn't. Fortunately, that single statement can be a compound statement enclosed in a BEGIN ... END block.
You need to enclose the function body in a BEGIN ... END block to allow MySQL to see it as a single statement; you'll also perhaps need to precede and follow it with DELIMITER statements (depending on your client, as Mr. Berkowski points out):
DELIMITER //
CREATE FUNCTION capitalize(string TEXT)
RETURNS TEXT
BEGIN
DECLARE first_letter TEXT;
DECLARE last_letters TEXT;
SET first_letter = UPPER(LEFT(string,1));
SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
RETURN CONCAT(first_letter, last_letters);
END; //
DELIMITER ;
(Note especially the space between the last DELIMITER and the semicolon.)
I'am developing a small project with PHP and MySql on a Wamp server. I just discovered the wonderful principle of SQL triggers. Hum... well. It would be wonderful if I could use it.
Indeed I have a problem with the following script:
BEGIN
SET #liste = NEW.reponse
WHILE LEN(#liste) > 0
BEGIN
IF PATINDEX('%,%',#liste) > 0
BEGIN
SET #choix = SUBSTRING(#liste, 0, PATINDEX('%,%', &liste))
INSERT INTO resultat (referendum, choix) VALUES (NEW.id, #choix)
SET #liste = SUBSTRING(#liste, LEN(#choix + ',') + 1, LEN(#liste))
END
END
END
I would like to execute this trigger after the insertion of a record in table "Referendum". In this table, there is a field "reponse" which contains the different possible answers. This field contains this kind of data: "Yes,No,I don't know". For each new question, I want to insert a new record in table "Resultat" per possible answer.
In my example, three new records: one for Yes, one for No and one for I don't know.
My code comes from an example on the internet but it doesn't work properly. SQL returns a syntax error with message "While_Sym expected"...
I tried to add semicolon following what I found on the internet but no way...
I guess you need something like this:
CREATE TRIGGER mytrigger AFTER INSERT
ON Referendum FOR EACH ROW
BEGIN
DECLARE cnt int;
DECLARE str varchar(100);
Set cnt = CHAR_LENGTH(NEW.reponse)
- CHAR_LENGTH(Replace(NEW.reponse,',','')) +1;
WHILE cnt > 0 DO
Set str = SUBSTRING_INDEX(
SUBSTRING_INDEX( New.reponse,',', -cnt)
,',',1);
INSERT INTO resultat (referendum, choix)
VALUES (NEW.id, str);
Set cnt = cnt - 1;
END WHILE;
END;
Demo: http://sqlfiddle.com/#!2/c7321/1
Some thoughts:
There are no PATINDEX nor LEN functions in MySql, they come from SQL Server.
Most functions are not standard in SQL, one shouldn't expect that something that works on database X should also work on database Y (and vice versa)
You always need to check the manual.
There is difference in MySql between #variable and variable - they are not the same (opposite to SQL Server where there is only one kind of variables --> #variable).
Please refer to documentation to learn about #user_definied_variables and local_variables
http://dev.mysql.com/doc/refman/5.7/en/user-variables.html
http://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html
Depending on your client software you may need to use also DELIMITER xx command, for example in mysql console client or MySql-Workbench you need something like this to create a trigger without syntax errors:
DELIMITER $$
CREATE TRIGGER mytrigger AFTER INSERT
ON Referend ......
......
......
END;
$$
DELIMITER ;
this is my code :
CREATE TRIGGER Zmiana_kategorii
ON Hotele
AFTER UPDATE
AS
BEGIN
DECLARE #stara smallint, #nowa smallint
IF COL_LENGTH('deleted', 'IloscGwiazdek')
BEGIN
SET #stara=(SELECT IloscGwiazdek FROM deleted)
SET #nowa=(SELECT IloscGwiazdek FROM inserted)
IF(#stara<#nowa)
BEGIN
print 'Powiadom następujących klientów o zmianie klasy hotelu'
declare #data date
SET #data=(CONVERT (date, GETDATE()))
SELECT KlientID FROM Rezerwacje Where #data<DataPrzyjazdu
END
END
END
could someone tell me what is wrong in syntax? I am 1st time using MYSQL i have no clue whats is wrong with this...
this is error : ON Hotele AFTER UPDATE AS BEGIN DECLARE #stara smallint, #nowa smallint ' at line 2" this is error
At least one problem is that you don't include the THEN after your IF conditions. For example:
IF (#stara<#nowa) THEN
BEGIN
-- ...
END
Another problem is that you have the order of the CREATE TRIGGER elements wrong. It should be:
CREATE TRIGGER Zmiana_kategorii
AFTER UPDATE
ON Hotele
Note that the AFTER UPDATE goes before the ON. This seems to solve your specific problem.
Finally, MySQL doesn't have a PRINT command and all variables have to be declared at the beginning of a BEGIN block, before any other statements.
Please read this entire page and understand what's going on: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
If you understand the syntax, then you can debug it yourself. These types of simple problems shouldn't require community assistance (though sometimes an extra pair of eyes can catch an obvious error).
Over the last couple of days I have tried to write an Stored procedure in MySQL and I have some truble getting it to work. Hope someone here can give me some input :)
The example I post is for asp.Net Membership provider to create a new user. I expect to send email and password to the DB and get an int return to verify that the userdeatils was written to the DB.
I use a MySQL DB 5.1 (I think) and write the SQL to a webinterface.
I got 2 sidequestions, can someone explain that too :):
1) I use a DELIMITER, but do not know what it does.
2) I am not sure if I have to do other things then to set autocommit = 0 to get transactions to work, or if I even have to do that.
I know that I could have used a IF / ELSE statement instead of a transaction, but would like to do it with one to find out how it works. (I expect to use it alot later)
The code I can not get to work:
DELIMITER //
CREATE DEFINER=`websharp_dk`#`%` PROCEDURE `CreateUser`(
IN _username VARCHAR(100),
IN _Password VARCHAR(100))
RETURNS INT
BEGIN
SET autocommit = 0;
DECLARE return_value INT;
BEGIN TRY
START TRANSACTION
INSERT INTO User
(Email
,Password
,Failed_Password_Count
,Creation_Date)
VALUES
(_username
,_Password
,0
,Datetime.Now())
SET return_value = 1;
COMMIT;
END TRY
BEGIN CATCH
ROLLBACK
SET return_value = 0;
END CATCH
BEGIN FINALLY
RETURN return_value;
END FINALLY
END//
DELIMITER ;
Edit:
The error message I get is:
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 'INT BEGIN SET autocommit = 0; DECLARE return_value INT; ' at line 4
To get support for transactions, make sure you are using the InnoDB storage engine rather than the default MyISAM.
As far as that code itself, my first question would be, why are you wrapping that single query in a transaction? Also, what errors are you seeing?
The delimiter redefines what sequence of characters you use to end an sql statement. The entire create procedure is one big statement and you need to tell MySQL where it ends with something (would normally be ';'). But since you have a bunch of other statements in the "body" (between BEGIN and END) of the create procedure statement that all need to be ended too you need to redefine the delimiter so you don't end the create procedure statement at the first ';'.
Without redefining the delimiter, MySQL would think that the create procedure statement looked like this and then begin a new statement:
CREATE DEFINER=`websharp_dk`#`%` PROCEDURE `CreateUser`(
IN _username VARCHAR(100),
IN _Password VARCHAR(100))
RETURNS INT
BEGIN
SET autocommit = 0;
Using DELIMITER ; at the end of the script changes the delimiter back to ';' and is not needed although it's good practice to do so.