I have the same code below:
CREATE PROCEDURE TEST1
(#id INT, #name NVARCHAR(30) OUTPUT)
AS
SELECT #name = NAME
FROM TEACHER
WHERE ID = #id;
AND
CREATE PROCEDURE TEST2(#id INT)
AS
DECLARE #name NVARCHAR(30);
SELECT #name = NAME
FROM TEACHER
WHERE ID = #id;
RETURN #name;
The top code is OK, but the second I get an error :
Msg 245, Level 16, State 1, Procedure TEST2, Line 174
Conversion failed when converting the nvarchar value 'Nguyễn Thanh Tùng' to data type int.
Can you help me explain and fix it ??
You cannot return a varchar from a SQL Server stored procedure using RETURN - you can only return integer values.
See the MSDN documentation on "Returning Data Using a Return Code" which clearly states:
A procedure can return an integer value called a return code to indicate the execution status of a procedure.
Typically, such a value is used to either indicate the number of rows affected by your stored procedure, or to indicate an error code.
If you need to return a string, you have to use either an OUTPUT parameter, or return a result set (using a SELECT statement).
Related
I am getting this error message
RETURN statements in scalar valued functions must include an argument
when run this query:
create function gender(#gender nvarchar(40))
returns nvarchar(40)
as
begin
(select name,cast(DOB as date) as DOB from datenames where gender = #gender)
return
end
The write way to create a function in mysql for your example is as follows:
DELIMITER \\
create function gender(Igender nvarchar(40))
returns nvarchar(40)
begin
DECLARE customerLevel NVARCHAR(40);
IF EXISTS (select name,cast(DOB as date) as DOB from datenames where gender = Igender) THEN
SET customerLevel = 'SOMETHING1';
ELSE
SET customerLevel = 'SOMETHING2';
END IF;
RETURN (customerLevel);
end
No need to as
No need to # before input
You need to return something.
Don't forget to use DELIMITER.
If you use phpmyadmin and has problem with nvarchar read this post: Unrecognize data type nvarchar in database or simply change it to to varchar.
If I have a TABLE named MyTable which has columns say C1(type date) and C2 (type character) I want to create a stored function that takes an input and the input should always belong to C1, and the output of the stored function should be the corresponding element in C2. I have tried to do it using the 'select' statement followed by 'where' clause inside the stored function but was not able to achieve it. Is there any other way to accomplish this task.
DELIMITER $$
CREATE FUNCTION `MyFunction`
(`Date` datetime)
RETURNS char(10)
BEGIN
DECLARE MyVariable char(10)
SELECT MyVariable = `C2`
FROM MyTable
WHERE `Date` = `C1`; RETURN MyVariable;
END$$
DELIMITER ;
But this keeps giving me ERROR CODE: 1064
At first glance, I see a syntax error:
...
BEGIN
DECLARE MyVariable char(10) <-- needs a semicolon here
SELECT MyVariable = `C2`
...
Every statement within the body of your routine must end with a semicolon. See examples of DECLARE in this manual page: https://dev.mysql.com/doc/refman/8.0/en/local-variable-scope.html
It should be like this:
...
BEGIN
DECLARE MyVariable char(10);
SELECT MyVariable = `C2`
...
Re your comment:
Error 1415 means "cannot return a result set". Your stored function is doing a SELECT without putting the result into your declared local variable using an INTO keyword.
You appear to be trying to set the value of MyVariable using = but that's just making a comparison. It doesn't assign anything to MyVariable.
Without using INTO to assign the variable, your SELECT statement is by default returning a result set. This is allowed in a stored procedure, but not in a stored function. A stored function must return a single scalar value, not a result set.
...
BEGIN
DECLARE MyVariable char(10);
SELECT `C2` INTO MyVariable
FROM MyTable
WHERE `Date` = `C1`;
RETURN MyVariable;
END
P.S.: I edited your question to replace the term "user-defined function" with "stored function". These are two different things in MySQL. You are writing a stored function.
In MySQL, they use the term user-defined function (UDF) for a function you implement in C/C++ code and compile into the MySQL server. It's less common for developers to write this type of extension.
I am trying to write a Mysql Function to return a contactID if the record exists based on the parameters supplied, If the record is not present, I am adding the record and then returning the contactID of the new record.
But the function is throwing 1048error, Can you check and correct me if I went wrong in writing this.
DELIMITER $$
CREATE DEFINER=`root`#`%` FUNCTION `GetContactID`(accountNumber CHAR(45),UserID INT(11)) RETURNS char(1) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE ContactID INT DEFAULT 0;
SELECT ContactID INTO #ContactID FROM Contact WHERE AccountNumber = #accountNumber AND UserID = #UserID AND Status =1;
IF ContactID = 0 or ContactID is null THEN
INSERT INTO Contact(AccountNumber,UserID) VALUES (#accountNumber,#UserID);
SELECT ContactID INTO #ContactID FROM Contact WHERE AccountNumber = #accountNumber AND UserID = #UserID;
END IF;
RETURN ContactID;
END
Can someone help me where I went wrong.
Thanks
The problem results from mixing user variables, local variables and parameters.
#UserId is not the same as UserId - they are different variables.
UserId is also a name of column in the table.
User defined variables are wirtten as #var_name, are stored in the user session and can be used to pass values between differend stored routines that reference them, see this link for details: http://dev.mysql.com/doc/refman/5.7/en/user-variables.html
local variables are declared in stored routines using DECLARE keyword, their scope is local within the stored routine, see this link for details: http://dev.mysql.com/doc/refman/5.7/en/declare-local-variable.html
Parameters of function/procedure - they are declared in the procedure/function declaration, they are used to pass parameters to the stored routine from the caller, can be also used to return results from the routine to the caller (if declared as OUT or INOUT). Their scope is similar to local variables. For details see this link: http://dev.mysql.com/doc/refman/5.7/en/create-procedure.html
Try this code:
DELIMITER $$
CREATE DEFINER=`root`#`%` FUNCTION `GetContactID`(p_accountNumber CHAR(45),p_UserID INT(11)) RETURNS char(1) CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE v_ContactID INT DEFAULT 0;
SELECT ContactID INTO v_ContactID
FROM Contact
WHERE AccountNumber = p_accountNumber AND UserID = p_UserID AND Status =1;
IF v_ContactID = 0 or v_ContactID is null THEN
INSERT INTO Contact(AccountNumber,UserID)
VALUES (p_accountNumber,p_UserID);
SELECT ContactID INTO v_ContactID FROM Contact
WHERE AccountNumber = p_accountNumber AND UserID = p_UserID;
END IF;
RETURN v_ContactID;
END;
Notice that:
function parameters are declared with prefix p_
local variables are declared with prefix v_
the function doesn't use any user variables (prefixed by #)
These prefixes help to avoid ambiguity - we know that p_UserID is a parameter, v_UserId is a local variable, and UserID is a column name in the table (If we would use #UserId, we knew that this was the user variable).
Does anybody know if this is allowed?
IF CALL GET_RIGHT_NODE(edge) = 15
THEN
SELECT "IT WORKS";
I'm getting an error on this syntax, is it possible any other way?
The return values from stored procedures should be captured in OUT paramters (whereas those from user defined functions can be captured as #returnValue = function()).
So, your GET_RIGHT_NODE should take an OUT parameter and set it to the return value.
CREATE PROCEDURE GET_RIGHT_NODE
(
#edge INT,
#returnValue INT OUTPUT
)
AS
-- Definition of the proc.
then you would call the procedure as follows:
DECLARE #returnValue INT
CALL GET_RIGHT_NODE(#edge, #returnValue)
IF (#returnValue = 15)
THEN
SELECT 'IT WORKS'
So, I'm making my first MySQL function.
BEGIN
DECLARE ID INT;
SELECT
LandID INTO ID
FROM
Landen
WHERE
Landnaam = landnaam;
RETURN ID;
END
The parameter is a varchar.
So, let's say I got a record in Landen with the Landnaam 'Nederland'.
I run my function, give 'Nederland' as parameter.
But then it gives me to following error:
1172 - result consisted of more than one row
Which makes no sense at all. Cause when I give something as a parameter that is not in my database, like 'ASDASD', I get the same error.
And when limmiting the results with
LIMIT 1
It just always returns 1.
What am I doing wrong?
drop function if exists myfunc;
delimiter //
create function myfunc(str varchar(50))
returns int
reads sql data
begin
declare id int;
select landid into id from Landen where landnaam = str limit 1;
return id;
end//
delimiter ;
select myfunc('nederland');