How to fix error in procedure SQL? - mysql

there is a hranimka, when it was created, an error occurs. Maybe she who struck by the ...
The stored procedure:
CREATE PROCEDURE insert_log(
IN LogType INT,
IN LogIdNote INT,
IN LogName VARCHAR,
IN LogTime TIMESTAMP,
IN logTypeCategory INT,
IN LogIdUser INT)
begin
INSERT INTO log (LogType,
LogIdNote,
LogName,
LogTime,
logTypeCategory,
LogIdUser,
LogTypeUser,
LogUrl)
SELECT LogType, LogIdNote, LogName, LogTime, logTypeCategory, LogIdUser, url.URLCategorysubscribetotype, u.UsersTypeAccount FROM users u LEFT JOIN categorysubscribetotype url ON url.CategoryTypeCategorysubscribetotype = LogType WHERE u.idUsers = LogIdUser;
end //
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 'INT LogType, INT LogIdNote, VARCHAR LogName, TIMESTAMP LogTime,
I' at line 3
I tried only change data types at params.
I think, the next code will give me a good result, but I need save result from SELECT query at variable and insert it at query Insert:
DELIMITER |
CREATE PROCEDURE insert_log(
IN pLogType INT,
IN pLogIdNote INT,
IN pLogName VARCHAR(150),
IN pLogTime TIMESTAMP,
IN plogTypeCategory INT,
IN pLogIdUser INT)
BEGIN
DECLARE user_type INT DEFAULT 0;
DECLARE url VARCHAR(250) DEFAULT;
SET user_type = (SELECT UsersTypeAccount FROM users WHERE idUsers = pLogIdUser);
SET url = (SELECT URLCategorysubscribetotype FROM categorysubscribetotype WHERE CategoryTypeCategorysubscribetotype = pLogType);
INSERT INTO log (pLogType,
pLogIdNote,
pLogName,
pLogTime,
plogTypeCategory,
pLogIdUser,
pLogTypeUser,
pLogUrl)
VALUES (
LogType,
LogIdNote,
LogName,
LogTime,
logTypeCategory,
LogIdUser,
user_type,
url
);
END |
delimiter ;

Your issue is here:
INSERT INTO log (pLogType, //wrong!
pLogIdNote,
pLogName,
pLogTime,
plogTypeCategory,
pLogIdUser,
pLogTypeUser,
pLogUrl)
You have used the parameter as column while they should be VALUES try this Query
DELIMITER //
CREATE PROCEDURE insert_log(
IN pLogType INT,
IN pLogIdNote INT,
IN pLogName VARCHAR(150),
IN pLogTime TIMESTAMP,
IN plogTypeCategory INT,
IN pLogIdUser INT)
BEGIN
DECLARE user_type INT DEFAULT 0;
DECLARE url VARCHAR(250) DEFAULT;
SET user_type = (
SELECT UsersTypeAccount
FROM users
WHERE idUsers = pLogIdUser
);
SET url = (
SELECT URLCategorysubscribetotype
FROM categorysubscribetotype
WHERE CategoryTypeCategorysubscribetotype = pLogType
);
INSERT INTO log (
`LogType`,
`LogIdNote`,
`LogName`,
`LogTime`,
`logTypeCategory`,
`LogIdUser`,
`LogIdUserType`, /*I added this*/
`LogIdUrl`, /*this one too */
)VALUES (
pLogType,
pLogIdNote,
pLogName,
pLogTime,
plogTypeCategory,
pLogIdUser,
user_type,
url
);
END //
DELIMITER ;
Please note You need to adjust this stored procedure, there was few mistakes. for example pLogTypeUser and pLogUrl are undefined and I added comments where you need to change the column name.

Your syntax is wrong. The data types come after the parameter names, the IN/OUT specifiers come before. Something like this:
CREATE PROCEDURE insert_log(
IN LogType INT,
IN LogIdNote INT,
IN LogName VARCHAR(10),
IN LogTime TIMESTAMP,
IN logTypeCategory INT,
IN LogIdUser INT)
begin
...
Edit: Also note that I added a size specifier to the VARCHAR data type, since it requires one. I guessed at 10, but you can replace that value with whatever yours is.

Related

Problem in returning values with my procedure

The following procedure is not returning values. Whats wrong?
CREATE PROCEDURE `sp_ValidarLogin`
(pEmail VARCHAR(45),
pSenha VARCHAR(255),
OUT rId INT,
OUT rNome VARCHAR(45),
OUT rDataNascimento DATE)
SELECT #rId = ID,
#rNome = NOME,
#rDataNascimento = DATA_NASCIMENTO
FROM usuario
WHERE EMAIL = pEmail AND SENHA = pSenha;
CALL sp_ValidarLogin ('rcaldas.ti#gmail.com','1234', #id, #nome, #nascimento);--its correct
select #id, #nome, #nascimento;
You have to use := instead of = to assign values on SELECT:
CREATE PROCEDURE `sp_ValidarLogin` (
pEmail VARCHAR(45),
pSenha VARCHAR(255),
OUT rId INT,
OUT rNome VARCHAR(45),
OUT rDataNascimento DATE)
SELECT #rId := ID, #rNome := NOME, #rDataNascimento := DATA_NASCIMENTO
FROM usuario
WHERE EMAIL = pEmail AND SENHA = pSenha;
demo on dbfiddle.uk
Previous releases of MySQL made it possible to assign a value to a user variable in statements other than SET. This functionality is supported in MySQL 8.0 for backward compatibility but is subject to removal in a future release of MySQL.
When making an assignment in this way, you must use := as the assignment operator; = is treated as the comparison operator in statements other than SET.
source: https://dev.mysql.com/doc/refman/8.0/en/user-variables.html

mysql stored procedure checking if record exists

I created the following stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `add_summit`(IN `assoc_code` CHAR(5), IN `assoc_name` CHAR(50), IN `reg_code` CHAR(2), IN `reg_name` CHAR(100), IN `code` CHAR(20), IN `name` CHAR(100), IN `sota_id` CHAR(5), IN `altitude_m` SMALLINT(5), IN `altitude_ft` SMALLINT(5), IN `longitude` DECIMAL(10,4), IN `latitude` DECIMAL(10,4), IN `points` TINYINT(3), IN `bonus_points` TINYINT(3), IN `valid_from` DATE, IN `valid_to` DATE)
BEGIN
declare assoc_id SMALLINT(5);
declare region_id SMALLINT(5);
declare summit_id MEDIUMINT(8);
-- ASSOCIATION check if an association with the given code and name already exists
SELECT id INTO assoc_id FROM association WHERE code = assoc_code LIMIT 1;
IF (assoc_id IS NULL) THEN
INSERT INTO association(code, name) VALUES (assoc_code, assoc_name);
set assoc_id = (select last_insert_id());
END IF;
-- REGION check if a region with the given code and name already exists
SET region_id = (SELECT id FROM region WHERE code = reg_code AND name = reg_name AND association_id = assoc_id);
IF (region_id IS NULL) THEN
INSERT INTO region(association_id, code, name) VALUES (assoc_id, reg_code, reg_name);
set region_id = (select last_insert_id());
END IF;
-- SUMMIT check if a summit with given parameters already exists
SET summit_id = (SELECT id FROM summit WHERE association_id = assoc_id AND region_id = region_id);
IF (summit_id IS NULL) THEN
INSERT INTO summit(code, name, sota_id, association_id, region_id, altitude_m, altitude_ft, longitude,
latitude, points, bonus_points, valid_from, valid_to)
VALUES (code, name, sota_id, assoc_id, region_id, altitude_m, altitude_ft, longitude, latitude,
points, bonus_points, valid_from, valid_to);
END IF;
END$$
basically, it should check if a record exists in some tables and, if it doesn't, it should insert it and use the inserted id (auto increment).
The problem is that even if the record exists (for instance in the association table), assoc_id keeps returning null and that leads to record duplication.
I'm new to stored procedures so I may be doing some stupid errors. I've been trying to debug this SP for hours but I cannot find the problem.
A newbie mistake.
I forgot to specify the table name in the field comparison and that leads to some conflicts with param names (for example the param name).
A good idea is to specify some kind of prefix for parameters (like p_) and always specify the name of the table in the SP.

Create an Store Procedure for Insert-Update in Mysql

I'm trying to create a stored procedure to insert or update a record based on an input variable. But when I try to compile the SP simply tells me the following: Code 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'' at line 80. And I have not found the solution. Thank you very much for any help you can give me.
My SP code is as follows:
DELIMITER $$
CREATE PROCEDURE `sp_sertup`(IN i_operation CHAR(1),
IN i_system VARCHAR(20),
IN i_subsystem VARCHAR(20),
IN i_ref VARCHAR(20),
IN i_significance VARCHAR(20),
IN i_rank VARCHAR(20),
IN i_implication VARCHAR(20),
IN i_loc1 VARCHAR(20),
IN i_loc2 VARCHAR(20),
IN i_task VARCHAR(20),
IN i_time VARCHAR(20),
IN i_cost1 VARCHAR(20),
IN i_cost2 VARCHAR(20),
IN i_note VARCHAR(20),
IN i_attach VARCHAR(20),
IN i_operation_text VARCHAR(20),
IN i_id_setup INT )
BEGIN
IF (i_operation = 'I') THEN
UPDATE setup_gs SET setup_status = 0 WHERE id_setup = id_setup;
INSERT INTO setup_gs(
SystemLabel,
SubsystemLabel,
RefLabel,
SignificanceLabel,
RankLabel,
ImplicationLabel,
Location1Label,
Location2Label,
TaskLabel,
TimeLabel,
Cost1Label,
Cost2Label,
NoteLabel,
attachmentText,
OperationsText,
setup_status
)
VALUES
(
i_system,
i_subsystem,
i_ref,
i_significance,
i_rank,
i_implication,
i_loc1,
i_loc2,
i_task,
i_time,
i_cost1,
i_cost2,
i_note,
i_attach,
i_operation_text,
1);
IF (i_operation = 'U') THEN
UPDATE
setup_gs
SET
SystemLabel = values(i_system),
SubsystemLabel = values(i_subsystem),
RefLabel = values(i_ref),
SignificanceLabel = values(i_significance),
RankLabel = values(i_rank),
ImplicationLabel = values(i_implication),
Location1Label = values(i_loc1),
Location2Label = values(i_loc2),
TaskLabel = values(i_task),
TimeLabel = values(i_time),
Cost1Label = values(i_cost1),
Cost2Label = values(i_cost2),
NoteLabel = values(i_note),
attachmentText = values(i_attach),
OperationsText = values(i_operation_text),
setup_status = 1
WHERE id_setup = i_id_setup;
END $$
DELIMITER ;
You must finish your IF-statements with END IF in MySQL.
Also, one of your tests is between id_setup and id_setup. It should be between id_setup and i_id_setup.
if you want to create a update stored procedure then follow these steps in mysql command line. it is work perfectly.
create procedure procedure_name(id int, name varchar(40),salary float)
update table_name set name=name,salary=salary from id=id;
firstly you need to create a table. after that write the keyword create procedure and after that write procedure_name() inside the procedure function write the column name.
i took id, name, salary inside the procedure and also provide the type of all after that i wrote simple query that is update table_NAME set name=name, salary=salary where id=id . because i want to change the name and salary of this id. now you use.

Table type parameter in a stored procedure cause operand type clash error

I want to give an array of identifiers as argument to a stored procedure.
The stored procedure looks like :
ALTER PROCEDURE [dbo].[SearchPerson]
#personType INT = NULL,
#city NVARCHAR(64) = NULL,
#siteIds IntegerList READONLY,
-- some other params...
AS
SELECT
-- some fields...
FROM dbo.PersonView AS pv
WHERE
(
(#personType IS NULL OR pv.PersonType = #personType) AND
(#city IS NULL OR pv.City LIKE '%' + #city + '%') AND
(pv.SiteId in (SELECT si.Value FROM #siteIds AS si)) AND
-- some other params filter...
)
The user table type looks like :
CREATE TYPE [dbo].[IntegerList] AS TABLE(
[Value] [int] NULL
)
When I call the stored procedure from a script in SSMS (I originally have the same problem calling it from .NET code) :
DECLARE #siteIds AS IntegerList,
#personType AS INT = 1
INSERT INTO #siteIds VALUES (1)
EXEC [dbo].[SearchPerson] #personType, #siteIds
I got the error :
Operand type clash: int is incompatible with IntegerList
I found the answer : it was the order of the table type parameter that caused the error !
The table type parameter must be the first in the stored procedure parameters AND ALSO in the arguments passed to the stored procedure call !
The stored procedure :
ALTER PROCEDURE [dbo].[SearchPerson]
#siteIds IntegerList READONLY, -- THIS PARAMETER HAS TO BE THE FIRST !
#personType INT = NULL,
#city NVARCHAR(64) = NULL,
-- some other params...
AS
SELECT
-- some fields...
FROM dbo.PersonView AS pv
WHERE
(
(#personType IS NULL OR pv.PersonType = #personType) AND
(#city IS NULL OR pv.City LIKE '%' + #city + '%') AND
(pv.SiteId in (SELECT si.Value FROM #siteIds AS si)) AND
-- some other params filter...
)
And the call :
DECLARE #siteIds AS IntegerList,
#personType AS INT = 1
INSERT INTO #siteIds VALUES (1)
EXEC [dbo].[SearchPerson] #siteIds, #personType -- PUT #siteIds FIRST !
A sql server bug or am I missing something ?
DECLARE #ErrMsg varchar(1000)
DECLARE #ServiceDates ServiceDatesType
INSERT #ServiceDates (indexId,unitOfDay,dayOfMonth,dateOfMonth)
VALUES
(0,1,11,'9/11/2016 12:00:00 AM'),
(1,1,12,'9/12/2016 12:00:00 AM'),
(2,1,13,'9/13/2016 12:00:00 AM')
EXEC [usp_SaveValidate] 427,4,12,9,2016,#ErrMsg output,#ServiceDates
PRINT #ErrMsg
*/
ALTER PROCEDURE [dbo].[usp_SaveValidate] (
#EpisodeNo INT
,#ProviderId INT
,#ServiceId INT
,#Month INT
,#Year INT
,#ErrorMessage VARCHAR(1000) OUTPUT
,#ServiceDates ServiceDatesType ReadOnly
)
AS
BEGIN
-- Code Here
END
SQL SERVER 2012 - location of table type parameter does not matter, you have to make sure sequence while passing data, you can check above code which is working fine where table type parameter is at the last.

Mysql Function returns Null always

I have a function in mysql like below:
DELIMITER $$
CREATE DEFINER=root#localhost FUNCTION fnGetDropDownValue(
itemValue varchar(300),
DropDownId int,
CId int
) RETURNS int(11)
BEGIN
DECLARE listId int;
SELECT ListID into listId FROM DropDownListValues WHERE LOWER(ListValue) = LOWER(itemValue) AND DropDownListID = DropDownId AND (ClientId = 0 OR ClientId = CId);
RETURN listId;
END$$
But it always returns Null values when I use
SELECT fnGetDropDownValue('General', 24, 18);
I don't know what I am doing wrong :(
After having the case sensitive issue with mysql columns I used to have variable names to start with _ to avoid it messing with column names. Now the stored procedure looks like this:
DELIMITER $$
CREATE DEFINER=root#localhost FUNCTION fnGetDropDownValue(
itemValue varchar(300),
DropDownId int,
CId int
) RETURNS int(11)
BEGIN
DECLARE _listId int;
SELECT ListID into _listId FROM DropDownListValues WHERE LOWER(ListValue) = LOWER(itemValue)
AND DropDownListID = DropDownId AND (ClientId = 0 OR ClientId = CId);
RETURN _listId;
END$$
This way it will work on any platform and it may be useful for others.