MySQL Error pls-00103 - mysql

I am making a MySQLand getting an error I dont know how to fix it. What the function should be doing is asking the user for input, this input should be stored in the corresponding variables and return a variable. But when i try run the function I am getting errors on the lines that store the variables. I am quite new to mySQL so i might be doing something stupid. Any help will be great thank you
This is is the mysql function
create or replace FUNCTION AD_AGENCY_INFO(agency_id in agency_id%type)
RETURN agency_id
DECLARE
v_no_of_runs AD_AGENCY.NO_OF_AD_RUNS%TYPE = '&enter_number_of_Runs';
v_credit_worthy AD_AGENCY.CREDIT_WORTHY%TYPE = '&enter_credit_worthy';
v_available_slots AD_AGENCY.AVAILABLE_SLOTS%TYPE = '&enter_available_slots';
v_status AD_AGENCY.STATUS%TYPE = '&enter_status';
BEGIN
insert into ad_agency values (agency_id, v_no_of_runs, v_credit_worthy,v_available_slots, v_status);
insert into ad (agency_id) values (agency_id);
commit;
RETURN (agency_id));
END AD_AGENCY_INFO;
The error that i am getting is the following and is the same for lines 7,8,9
Error(6,45): PLS-00103: Encountered the symbol "=" when expecting one of the following: := ( ; not null range default character The symbol ":= was inserted before "=" to continue.

Try changing your declare statement(s) to be
v_no_of_runs AD_AGENCY.NO_OF_AD_RUNS%TYPE := '&enter_number_of_Runs'

Related

Duplicate problem in MySQL with autoincrement id

I have an issue with my database.
Table structure is:
Table name: sales
sale_id (autoincrement)
date (datetime)
total (decimal)
etc.
I have 2 computers, one is "the server" and the other is "the client", when I Insert in "sales" sometimes the database saves more than 1 record, it's an issue kind of random because one day could be normal just save 1 record as is but other day could save 2 or more duplicates.
My code is:
qry1.SQL.Text := 'SELECT * FROM sales '
+ 'WHERE sale_id = 1';
qry1.Open;
qry1.Insert;
qry1.FieldByName('date').AsDateTime := Date;
qry1.FieldByName('total').AsFloat := total;
qry1.Post;
saleId := qry1.FieldByName('sale_id').AsInteger;
qry1.Close;
// Code to save sale details using saleId.
I'm using Delphi 10.3 + ZeosLib 7.2.6-stable + MySQL 8.0
I opened the ports in the server so I have a direct connection to MySQL, I don't know what could be happening
Hope you can help me
Update----
Thanks for your kind answers,
#nbk Yes, I did it already.
#A Lombardo I used "where" to get just 1 record and then I use the query to insert the new one similar to use TTable but instead of load the hole table I just get one record and I can insert (qry.Insert),
#TheSatinKnight not only I get two records, sometimes I get 3 or more, but makes sense probably the keayboard is not working well and could send "enter" key more than once.
#fpiette, I will do ti right now.
I will keep you posted.
There are better ways to accomplish an insert than to open a TZTable and inserting on that open table.
As another approach, drop 2 TZQuery (NOT TZTable) on your form (which I'll assume is TForm1 - change as appropriate).
Assuming the name is ZQuery1 and ZQuery2.
Set its connection property the same as your TZTable, so it uses the same connector.
Set ZQuery1.SQL property to 'Insert into sales (date, total) values (:pdate, :ptotal)' //(w/o quotes)
Set ZQuery2.SQL property to 'select last_insert_id() as iddb'
now add the Function below to your form's Private delcaration
TForm1 = class(TForm)
ZQuery1: TZQuery; //added when dropped on form
ZQuery2: TZQuery;
private
{ Private declarations }
function AddNewSale(SaleDate: TDateTime; Total: Double): Integer; //add this line
public
{ Public declarations }
end;
and then add the following code to your form's methods
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.AddNewSale(SaleDate: TDateTime; Total: Double): Integer;
begin
ZQuery1.ParamByName('pdate').AsDateTime := SaleDate;
ZQuery1.ParamByName('ptotal').AsFloat := Total;
ZQuery1.ExecSQL; //*Execute* the Insert - Only "open" SQL that returns a result set
//now the record has been added to your DB
if ZQuery1.RowsAffected = 1 then //check to ensure it was inserted
begin
ZQuery2.Open;
try
Result := ZQuery2.FieldByName('iddb').AsInteger;
finally
ZQuery2.Close;
end;
end
else
result := -1;//indicate error by returning negative value
end;
now in the place you want to insert the record, simply call this function:
var
ReturnValue: Integer;
begin
ReturnValue := AddNewSale(Date, total);
if ReturnValue < 0 then
//error happened
else
begin
//Everything worked
end;
end;
Thanks again for all your kind answers.
At the end the problem was keyboard, It had a problem with "Enter" key, so when you pressed it, it send more than one pulsation so #TheSatinKnigh your approach was correct
#fpiette I created the log file and I figured out as you said the request had been executed twice or more.
I know maybe it is a silly thing for a programmer because I was disabling the button to late, sorry for that
#A Lombardo thanks for you code I like it better than mine I will use it

"No Return Found" error in simple mysql function

I'm using xampp with phpMyAdmin to manage a MySql database.
When creating a function I got a "No Return Found" error, so I stripped down the function to narrow the origin of the error I got to the simplest case where it still doesn't work.
And the error message is this:
Apparently if the RETURN statement isn't the only thing on the code I get an error.
Assuming the actual code being executed against MySQL is:
CREATE FUNCTION `Contagem`() RETURNS INT(11)
SET #c = 0;
RETURN #c;
This will fail, because you have not wrapped the function in BEGIN...END.
Try instead to write this as your function declaration:
BEGIN
SET #c = 0;
RETURN #c;
END;
Alternatively, declare the function yourself directly in MySQL:
DELIMITER $$
CREATE FUNCTION `Contagem`() RETURNS INT(11)
BEGIN
SET #c = 0;
RETURN #c;
END $$
DELIMITER ;
When reviewing this post I was reading more carefully the error message I realized the MySql code to define the function didn't have BEGIN and END in it.
I assumed when typing function code with several lines that phpMyAdmin would know how to handle it, since the code text box has support to multiple lines of code.
So, putting BEGIN at the beginning and END at the end of the code solved my problem.

How to get this function to work in Oracle 11G - PL/SQL

I'm new with PL/SQL I have a assignment where I need to make a function. The assignment is as follows:
> "Create a function 'afdeling_van:'
> - this function accepts a medewerkernummer(employee number) as argument
> - give the afdelingnummer(department number) from the medewerkernummer(employee number) back"
So I need to create a function with a parameter that returns a number. After that I probably need to add some code to make it return a medewerker(employee) number back.
I got pretty stuck with this one as I am really new to PL/SQL. What I do have at the moment is this:
declare
procedure afdeling_van(p_persoon in medewerkers.mnr%type)--table name with column name
is
begin
select med.mnr
from medewerkers med;
where mnr = p_persoon;
end afdeling_van;
begin
afdeling_van(10);
end;
It's not working for me. I have tried different solutions. But as I lack experience and I cannot find the solution or information that I need on the web. I am trying it to ask here
one other thing. I think it's similair to my problem. In the previous assignment I made a procedure instead of a function. The procedure is as follows:
declare
v_medewerker varchar2(50) := ontsla_med();
procedure ontsla_med(p_medewerkers in medewerkers.naam%type)
is
begin
delete from medewerkers
where naam = p_medewerkers;
end ontsla_med;
begin
ontsla_med('');
dbms_output.put_line('Medewerker: ' || v_medewerker || 'verwijdert uit medewerker, inschrijven en uitvoeringen bestand.' );
exception
when no_data_found then
dbms_output.put_line('Medewerker bestaat niet/ is al verwijderd.');
end;
/
this works except for the last dbms_output.put_line. If I remove the output line, then it will work and with the output line, it won't.
I hope my question is not too vague.
Thanks in advance.
You need to create a function instead of a procedure, and you've got a semi-colon in the wrong place. Try something like:
declare
nReturned_value MEDEWERKERS.AFDELINGNUMMER%TYPE;
FUNCTION afdeling_van(p_persoon in medewerkers.mnr%type) --table name with column name
RETURN MEDEWERKERS.AFDELINGNUMMER%TYPE
is
nAFDELINGNUMMER MEDEWERKERS.AFDELINGNUMMER%TYPE;
begin
select med.AFDELINGNUMMER
INTO nAFDELINGNUMMER
from medewerkers med
where mnr = p_persoon;
RETURN nAFDELINGNUMMER ;
end afdeling_van;
begin
nReturned_value := afdeling_van(10);
DBMS_OUTPUT.PUT_LINE('nReturned_value = ' || nReturned_value);
end;
Edit
In your second example, I don't believe that the line v_medewerker varchar2(50) := ontsla_med(); will compile. ontsla_med is a procedure rather than a function, and because procedures don't return anything they can't be used in an assignment statement.
However, v_medewerker is only used in the DBMS_OUTPUT line which you say causes a problem - thus, it may be that the compiler is eliminating the variable because it's not used if the DBMS_OUTPUT line is removed, thus eliminating the problem. Try changing the declaration to v_medwerker varchar2(50) := 'Hello'; and see if that helps.

Case Insensitive REPLACE for MySQL

Is there a case insensitive Replace for MySQL?
I'm trying to replace a user's old username with their new one within a paragraph text.
$targetuserold = "#".$mynewusername;
$targetusernew = "#".$newusername;
$sql = "
UPDATE timeline
SET message = Replace(message,'".$targetuserold."', '".$targetusernew."')
";
$result = mysql_query($sql);
This is missing the instances where the old username is a different case. Example: replacing "Hank" with "Jack" in all the rows in my database will leave behind instances of "hank".
An easier way that works without any stored function:
SELECT message,
substring(comments,position(lower('".$targetuserold."') in message) ) AS oldval
FROM timeline
WHERE message LIKE '%".$targetuserold."%'
gives you the exact, case sensitive spellings of the username in all messages. As you seem to run that from a PHP script, you could use that to collect the spellings together with the corresponding IDs, and then run a simple REPLACE(message,'".$oldval.",'".$targetusernew."') on that. Or use the above as sub-select:
UPDATE timeline
SET message = REPLACE(
message,
(SELECT substring(comments,position(lower('".$targetuserold."') in message))),
'".$targetusernew."'
)
Works like a charm here.
Credits given to this article, where I got the idea from.
Here it is:
DELIMITER $$
DROP FUNCTION IF EXISTS `replace_ci`$$
CREATE FUNCTION `replace_ci` ( str TEXT,needle CHAR(255),str_rep CHAR(255))
RETURNS TEXT
DETERMINISTIC
BEGIN
DECLARE return_str TEXT DEFAULT '';
DECLARE lower_str TEXT;
DECLARE lower_needle TEXT;
DECLARE pos INT DEFAULT 1;
DECLARE old_pos INT DEFAULT 1;
SELECT lower(str) INTO lower_str;
SELECT lower(needle) INTO lower_needle;
SELECT locate(lower_needle, lower_str, pos) INTO pos;
WHILE pos > 0 DO
SELECT concat(return_str, substr(str, old_pos, pos-old_pos), str_rep) INTO return_str;
SELECT pos + char_length(needle) INTO pos;
SELECT pos INTO old_pos;
SELECT locate(lower_needle, lower_str, pos) INTO pos;
END WHILE;
SELECT concat(return_str, substr(str, old_pos, char_length(str))) INTO return_str;
RETURN return_str;
END$$
DELIMITER ;
Usage:
$sql = "
UPDATE timeline
SET message = replace_ci(message,'".$targetuserold."', '".$targetusernew."')
";
My solution ultimately was that I cannot do a case insensitive Replace.
However, I did find a workaround.
I was trying to have a feature where a user can change their username. The system would then need to update wherever #oldusername was found in all the messages in the database.
The problem was... people wouldn't type other people's usernames in the correct case that it is found in the members table. So when the user would change their username, it wouldn't catch those instances of #oldSeRNAmE because of it not matching the case of the real format of the oldusername.
I don't have permission with my GoDaddy shared server to do this with a customized SQL function, so I had to find a different way.
My solution: Upon inserting new messages into the database, whenever a username is found in the new message, I have an UPDATE statement at that point to replace the username they typed with the correct formatted case that is found in the members table. That way, if that person ever wants to change their username in the future, all the instances of that username in the database will all be the same exact formatted case. Problem solved.

function return varray error

I keep getting a error when i run this code, What wrong with the code?
create or replace function f_vars(line varchar2,delimit varchar2 default ',')
return line_type is type line_type is varray(1000) of varchar2(3000);
sline varchar2 (3000);
line_var line_type;
pos number;
begin
sline := line;
for i in 1 .. lenght(sline)
loop
pos := instr(sline,delimit,1,1);
if pos =0 then
line_var(i):=sline;
exit;
endif;
string:=substr(sline,1,pos-1);
line_var(i):=string;
sline := substr(sline,pos+1,length(sline));
end loop;
return line_var;
end;
LINE/COL ERROR
20/5 PLS-00103: Encountered the symbol "LOOP" when expecting one of
the following:
if
22/4 PLS-00103: Encountered the symbol "end-of-file" when expecting
one of the following:
end not pragma final instantiable order overriding static
member constructor map
Stack Overflow isn't really a de-bugging service.
However, I'm feeling generous.
You have spelt length incorrectly; correcting this should fix your first error. Your second is caused by endif;, no space, which means that the if statement has no terminator.
This will not correct all your errors. For instance, you're assigning something to the undefined (and unnecessary) variable string.
I do have more to say though...
I cannot over-emphasise the importance of code-style and whitespace. Your code is fairly unreadable. While this may not matter to you now it will matter to someone else coming to the code in 6 months time. It will probably matter to you in 6 months time when you're trying to work out what you wrote.
Secondly, I cannot over-emphasise the importance of comments. For exactly the same reasons as whitespace, comments are a very important part of understanding how something works.
Thirdly, always explicitly name your function when ending it. It makes things a lot clearer in packages so it's a good habit to have and in functions it'll help with matching up the end problem that caused your second error.
Lastly, if you want to return the user-defined type line_type you need to declare this _outside your function. Something like the following:
create or replace object t_line_type as object ( a varchar2(3000));
create or replace type line_type as varray(1000) of t_line_type;
Adding whitespace your function might look something like the following. This is my coding style and I'm definitely not suggesting that you should slavishly follow it but it helps to have some standardisation.
create or replace function f_vars ( PLine in varchar2
, PDelimiter in varchar2 default ','
) return line_type is
/* This function takes in a line and a delimiter, splits
it on the delimiter and returns it in a varray.
*/
-- local variables are l_
l_line varchar2 (3000) := PLine;
l_pos number;
-- user defined types are t_
-- This is a varray.
t_line line_type;
begin
for i in 1 .. length(l_line) loop
-- Get the position of the first delimiter.
l_pos := instr(l_line, PDelimiter, 1, 1);
-- Exit when we have run out of delimiters.
if l_pos = 0 then
t_line_var(i) := l_line;
exit;
end if;
-- Fill in the varray and take the part of a string
-- between our previous delimiter and the next.
t_line_var(i) := substr(l_line, 1, l_pos - 1);
l_line := substr(l_line, l_pos + 1, length(l_line));
end loop;
return t_line;
end f_vars;
/