...

View Full Version : Resolved Role of variables in a stored procedure?



Oatley
03-29-2013, 12:33 PM
Hello, can someone please help me understand what the role defining variables does when it comes to using them with stored procedures.

For example if I write a stored procedure with a variable with a default value of Tim



DELIMITER //
CREATE PROCEDURE test()
BEGIN
DECLARE the_name VARCHAR( 255 ) DEFAULT 'Tim';
SELECT name from table where name = the_name;
END //


What's the difference between that and this where I define no variable



DELIMITER //
CREATE PROCEDURE test()
BEGIN
SELECT name from table where name = 'Tim';
END //


I can't quite see the difference and why you declare them? Can you pass in values to overwrite these default values and if no value is passed in it uses the default?

Can anyone help me understand the role of variables in stored procedures? Thank you.

BubikolRamios
03-29-2013, 09:49 PM
In your case it is pointless.

The use od declared variables comes in place where you need then and you can't use them unless they are declared: <-- this is the rule (EDIT: this applays to s.p. local variables)



DECLARE the_int_variable int DEFAULT 0;

Select max (fileld) into the_int_variable from table;
/*you can use that in further selects, stored proc cursor loops, conditions,....*/



one more example(suppose you have to do many slects using same date in condition):




DECLARE d DATETIME;

select max (datefield) into d from table;

select * from tab1 where datefield = d;
select * from tab2 where datefield = d;
select * from tab3 where datefield = d;
/*get it ? You are saving db resources here, not calling for date for condition each time*/




You can assign new value to variable at any time, default is there so you are able to check if it has changed during stored proc run.

Oatley
03-29-2013, 11:14 PM
Brilliant explanation. Thank you I fully understand now. :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum