someone can help me with procedure?
i get error:
Where is problem?
If you write a procedure with more than one statement in the body, you need to use BEGIN...END.
CREATE PROCEDURE addItemToRepository(IN name VARCHAR(50), IN rfid VARCHAR(20),
IN type VARCHAR(20), IN manufacturer INT, IN model VARCHAR(30), IN toRent TINYINT)
NOT DETERMINISTIC MODIFIES SQL DATA SECURITY DEFINER
BEGIN
SET #typeid = (SELECT id FROM dictionary WHERE value = type LIMIT 1);
INSERT INTO depository (name, rfidtag, type, manufacturer, model, torent)
VALUES (name, rfid, #typeid, manufacturer, model, torent);
END
Note I changed select(#typeid) in your insert statement. It's unnecessary to use select, and you can't do it without putting it inside a subquery in parentheses anyway.
I have some more comments:
Make sure your IN parameter names are distinct from your column names, or else you might create ambiguous SQL statements, that is MySQL doesn't know if you mean manufacturer the in parameter or manufacturer the column in the depository table. It's not an error, but it might insert a NULL because it's using manufacturer from the non-existing row. So I suggest the habit of naming in parameters with a prefix like "p" indicating parameter.
Declare a local variable instead of using session variables. MySQL treats them differently.
Consider using the alternative INSERT...SET syntax.
Here's my suggestion:
CREATE PROCEDURE addItemToRepository(IN pName VARCHAR(50), IN pRfid VARCHAR(20),
IN pType VARCHAR(20), IN pManufacturer INT, IN pModel VARCHAR(30), IN pToRent TINYINT)
NOT DETERMINISTIC MODIFIES SQL DATA SECURITY DEFINER
BEGIN
DECLARE vTypeid INT;
SELECT id INTO vTypeid FROM dictionary WHERE value = pType LIMIT 1;
INSERT INTO depository
SET name = pName,
rfidtag = pRfid,
type = vTypeid,
manufacturer = pManufacturer,
model = pModel,
toRent = pToRent;
END
Related
We have this option to pass table valued parameters in SQL Server Stored procedure.
For example :
CREATE OR ALTER PROCEDURE [dbo].[TestProcedure]
(
#Id INT,
#StartDate DATETIME,
#EndDate DATETIME,
#TestIds1 dbo.UserDefinedTableType1 READONLY,
#TestIds2 dbo.UserDefinedTableType2 READONLY
)
Do we have a similar option in MySQL?
Currently I am passing comma separated string as Text parameter and extracting from that.
For example, if I want
Id
1
2
I am passing,
'[{"Id":1},{"Id":2}]'
CALL TestProcedure
(
ID1,
'[{"Id":1},{"Id":2}]',
'[{"Id2":1}]',
'No'
);
and extracting like
SELECT *
FROM JSON_TABLE(Ids,"$[*]"
COLUMNS(Id INT PATH "$.Id")) AS XX;
I cannot figure out the proper syntax in this stored procedure. I declared the Course_id variable. One of the input values to the stored procedure is named csi. I want to use value of csi to lookup a value in another table. I am trying to retrieve the course_id from a table named course_schedule. If you look at the first SELECT statement in this procedure you'll see what I'm trying to do. I have tried different ways of syntax in the statement, but I can't get it to work.
Can someone give me clue where I am going wrong?
Thank you,
Mike Reed
CREATE DEFINER=`root`#`%` PROCEDURE `ClassRegistration`(IN csi numeric, IN regid numeric, IN area_id numeric, IN comm_id numeric, IN feeamount numeric, IN status CHAR(50), IN addby CHAR(50), IN addip CHAR(50) )
BEGIN
DECLARE course_regid INTEGER DEFAULT 0;
DECLARE course_id INTEGER DEFAULT 0;
SELECT course_id INTO #course_id FROM course_schedule WHERE course_sked_id = csi;
INSERT INTO course_registered (course_sked_id, regid, area_id, comm_id, status, feeamount, added, addby, addip, modified, modby, modip) values (csi, regid, area_id, comm_id, status, feeamount, now(), addby, addip, now(), addby, addip );
SELECT LAST_INSERT_ID() INTO course_regid;
SELECT course_id;
INSERT INTO student_eval (regid, course_sked_id) values (regid, csi);
INSERT INTO instructor_eval (regid, course_sked_id) values (regid, csi);
END
At the moment I'm working with databses and I got a strange error wirth procedures. I have create one which gets three parameters of the type VARCHAR: title, interpret, album. Here is the code:
BEGIN
INSERT IGNORE INTO Interpret (Name) VALUES (interpret);
SET #idInterpret := (SELECT id FROM Interpret WHERE Name = interpret);
INSERT IGNORE INTO Album (Name, Interpret) VALUES (album, #idInterpret);
SET #idAlbum := (SELECT id FROM Album WHERE Name = album AND Interpret = #idInterpret);
INSERT INTO Lied (Name, Album, Interpret) VALUES (title, #idAlbum, #idInterpret);
END
If I start this procedure I get an error which says that the album field can not be null (which is right) but it shouldn't be null because I read the value from the table above. If I call exact the same lines of SQL with real data (not as procedure with varaibles) all works great. Do you have any ideas why this happens?
Avoid naming variables and parameter as columns of your tables.
In your query:
SET #`idAlbum` := (SELECT `id`
FROM `Album`
WHERE `Name` = `album` AND `Interpret` = #`idInterpret`);
Interpret, are you referring to the parameter or column of the table?. We know that is column, MySQL interprets is the parameter.
SQL Fiddle demo
See:
13.6.4.2 Local Variable Scope and Resolution
Name Conflicts within Stored Routines in D.1 Restrictions on Stored Programs
Follow the comment #Bernd-Buffen using local varibales for this case.
To use vars in a Stored Procedure you must DECLARE it and then you
can use them without quotes. I have changed your Query, but not tested.
BEGIN
DECLARE idInterpret DEFAULT ='';
DECLARE idAlbum DEFAULT ='';
INSERT IGNORE INTO Interpret (Name) VALUES (interpret);
SELECT id IN TO idInterpret FROM Interpret WHERE Name = interpret;
INSERT IGNORE INTO Album (Name, Interpret) VALUES (album, idInterpret);
SELECT id INTO idAlbum FROM Album WHERE Name = album AND Interpret = idInterpret;
INSERT INTO Lied (Name, Album, Interpret) VALUES (title, idAlbum, idInterpret);
END
I'm playing around with MySQL stored procedures and I need a little help wrapping my head around some things. Below I'm attempting to;
1) Check if the student_id exist in the database and if it does then display "alumni already exist"
2) Check to see if the department and degree parameter entered don't exist and if it doesn't, then display "_ does not exist" (side note : these two columns are foreign keys)
Right now, my IF statement doesn't work and throws arbitrary errors. (ex. student_id doesn't exist in table but the error "Alumni Exist Already" is thrown, this is one of many)
I'd like to know what I'm doing wrong. Also, If the way I'm approaching this makes sense and if it doesn't, what's a more pragmatic way of going about this?
Thanks
DELIMITER //
DROP PROCEDURE IF EXISTS sp_add_alumni//
CREATE PROCEDURE sp_add_alumni (
IN student_id INT(20),
IN first_name VARCHAR(255),
IN last_name VARCHAR(255),
IN street VARCHAR(255),
IN city VARCHAR(255),
IN state VARCHAR(2),
IN zip_code VARCHAR(15),
IN email VARCHAR(255),
IN telephone VARCHAR(22),
IN degree VARCHAR(255),
IN department VARCHAR(255)
)
BEGIN
DECLARE studentID INT(20);
DECLARE departmentVAL VARCHAR(255);
DECLARE degreeVal VARCHAR(255);
DECLARE EXIT HANDLER FOR SQLWARNING
BEGIN
ROLLBACK;
SELECT 'ALUMNI INSERT HAS FAILED';
END;
SET studentID = student_id;
SET departmentVal = department;
SET degreeVal = degree;
IF EXISTS (SELECT 1 FROM alumni WHERE student_id = studentID ) THEN
SELECT 'ALUMNI ALREADY EXISTS';
ELSEIF NOT EXISTS (SELECT 1 FROM valid_departments WHERE UCASE(department) = UCASE(departmentVal)) THEN
SELECT 'DEPARTMENT DOES NOT EXISTS';
ELSEIF NOT EXISTS (SELECT 1 FROM valid_degrees WHERE UCASE(degree) = UCASE(degreevVal)) THEN
SELECT 'DEGREE DOES NOT EXISTS';
ELSE
SELECT 'ALUMNI ADDED';
END IF;
START TRANSACTION;
INSERT INTO alumni (student_id, pwd ,first_name, last_name, street, city, state, zip_code, email, telephone, degree, department, role_id, donation_total) VALUES (student_id, NULL ,first_name, last_name, street, city, state, zip_code, email, telephone, degree, department, 1, 0.00);
COMMIT;
END//
I'd like to know what I'm doing wrong.
As documented under Restrictions on Stored Programs:
Name Conflicts within Stored Routines
The same identifier might be used for a routine parameter, a local variable, and a table column. Also, the same local variable name can be used in nested blocks. For example:
CREATE PROCEDURE p (i INT)
BEGIN
DECLARE i INT DEFAULT 0;
SELECT i FROM t;
BEGIN
DECLARE i INT DEFAULT 1;
SELECT i FROM t;
END;
END;
In such cases, the identifier is ambiguous and the following precedence rules apply:
A local variable takes precedence over a routine parameter or table column.
A routine parameter takes precedence over a table column.
A local variable in an inner block takes precedence over a local variable in an outer block.
The behavior that variables take precedence over table columns is nonstandard.
In your case student_id is a routine parameter and studentID is a local variable; therefore (given the precedence rules above) the filter criterion WHERE student_id = studentID is comparing those two things with eachother and at no time is inspecting a table column.
Since the local variable was set to the value of the routine parameter, this filter always evaluates to true.
You could avoid this either by using different names for your parameters/variables, or else by qualifying your column reference with a table prefix:
WHERE alumni.student_id = studentID
Also, If the way I'm approaching this makes sense and if it doesn't, what's a more pragmatic way of going about this?
Define suitable UNIQUE and foreign key constraints, then attempts to insert invalid data will fail without you explicitly having to check anything:
ALTER TABLE alumni
ADD UNIQUE KEY (student_id), -- is this not already a PRIMARY KEY ?
ADD FOREIGN KEY (department) REFERENCES valid_departments (department),
ADD FOREIGN KEY (degree ) REFERENCES valid_degrees (degree )
;
To make the foreign keys use a case-insensitive lookup, ensure that the respective columns use a case insensitive collation.
Note the restrictions to which foreign keys are subject in the article linked above.
Mysql stored proc is
DELIMITER $$
CREATE DEFINER=`root`#`%` PROCEDURE `Check1`(
IN P_Name VARCHAR(50)
,OUT P_Id INT
)
BEGIN
INSERT INTO Company
(Name, Expiry, CreatedDate, Active)
VALUES
(P_Name, 90, NOW(), 1);
SET P_Id = ##identity;
END
Company TABLE has
CompanyID
Name
CreateDate
Active
as various columns
I need use VB .Net to call this procedure, insert value into the database and get the ID (primary key - company ID).
Whenever I insert a row, I need to retrieve the ID. Right now, I am able only to insert the row, but don't know how to call a SP with both input and output parameters from VB.
Check out the Direction member of OleDbParameter.