<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>TechTips &#187; MySQL</title>
	<atom:link href="http://kshitijsharma.net/category/netaspnetvbnetcsql-server-mysql/mysql-netaspnetvbnetcsql-server-mysql/feed/" rel="self" type="application/rss+xml" />
	<link>http://kshitijsharma.net</link>
	<description>.NET/ CSLA.NET / ASP.NET / VB.NET / C# / SQL Server / MySql ..</description>
	<lastBuildDate>Tue, 24 Aug 2010 15:37:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Stored Procedures in MySQL</title>
		<link>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/</link>
		<comments>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 08:31:18 +0000</pubDate>
		<dc:creator>Kshitij Sharma</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[store procedures]]></category>

		<guid isPermaLink="false">http://kshitijsharma.net/?p=69</guid>
		<description><![CDATA[<strong>So what exactly Stored Procedures are :</strong>
<ul>
	<li>Basically in a database management system (DBMS), a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time). Stored procedures have been part of Oracle, MS SQL Server, DB-2, postgreSQL and others for years but MySQL introduce Store procedures recently in version 5.xxx. MySQL stored procedures are very similar to the DB2 implementation, as both are based on the SQL:2003 standard.</li>
</ul>
]]></description>
			<content:encoded><![CDATA[<p><!-- You will NOT be able to see the ad on your site! This unit is hidden on your page, and will only display to your search engine traffic (from US and CA). To preview, paste the code up on your site, then add #chitikatest=mortgage to the end of your URL in your browser's address bar.  Example:  www.yourwebsite.com#chitikatest=mortgage. This will show you what the ad would look like to a user who is interested in "mortgages." -->
<script type="text/javascript"><!--
ch_client = "kshitijsharma";
ch_type = "mpu";
ch_width = 500;
ch_height = 250;
ch_noborders=0;
ch_non_contextual = 4;
ch_vertical ="premium";
ch_sid = "Chitika Premium";
var ch_queries = new Array( );
var ch_selected=Math.floor((Math.random()*ch_queries.length));
if ( ch_selected < ch_queries.length ) {
ch_query = ch_queries[ch_selected];
}
//--></script>
<script  src="http://scripts.chitika.net/eminimalls/amm.js" type="text/javascript">
</script><br />
<strong><B>So what exactly Stored Procedures are :</B></strong></p>
<ul>
<li>Basically in a database management system (DBMS), a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that&#8217;s stored in the database in compiled form so that it can be shared by a number of programs. The use of stored procedures can be helpful in controlling access to data (end-users may enter or change data but do not write procedures), preserving data integrity (information is entered in a consistent manner), and improving productivity (statements in a stored procedure only need to be written one time). Stored procedures have been part of Oracle, MS SQL Server, DB-2, postgreSQL and others for years but MySQL introduce Store procedures recently in version 5.xxx. MySQL stored procedures are very similar to the DB2 implementation, as both are based on the SQL:2003 standard.</li>
</ul>
<p><span id="more-69"></span></p>
<p align="left"><strong>Why i need store procedure when i can write Queries on page/formsÂ  :</strong></p>
<ul>
<li>Consider a scenario in which you have a client/server application with centrally located database server and your application has a provision to create a voucher and you calculate tax on the amount of the voucher. What if you need to change tax rate. Either you have to change code in your form to recalculate the tax and then you need to reinstall your forms on each of the client machine or you have an option to create a procedure that calculate tax and call that procedure from your client application and thatâ€™s it. Because your application call the procedure to calculate tax you donâ€™t need to reinstall your BO (Business Objects) or client application to each of client machine. All you need to do is to change code in your procedure that calculate Tax.<div style="display:block; float:left; margin: 0 15px 0 0;"><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 300x250_Medium_Rectangle, created 6/22/09 */
google_ad_slot = "9407728766";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></li>
<li>They can reduce network traffic. Complex, repetitive tasks may require getting results, applying some logic to them, and using this to get more results. If this only has to be done on the database server, there is no need to send result sets and new queries back and forth from application server to database server. Network traffic is a common bottleneck causing performance issues, and stored procedures can help reduce this. More often though, it is the database server itself that is the bottleneck, so this may not be much of an advantage.</li>
</ul>
<p><strong>Letâ€™s Start with a simple Example:</strong></p>
<p>As i described earlier a store procedure is a set of SQL Statement. Almost any valid SQL Statement can go inside a store procedure, with a few exceptions, which we will look later. I am using MySQL command line utility to write and execute procedures. You can also use MySQL Query Browser to create/modify/delete procedures. It comes with MySQL GUI Tools which are freely available on MySQL Site.</p>
<p><strong>use test; #Select Database<br />
CREATE PROCEDURE usp_test() SELECT &#8216;SP Test &#8216; as Title;<br />
</strong>This line will add a procedure called â€œusp_testâ€ in your selected database which in this case is Test. Note i use â€˜uspâ€™Â  (User store procedure) as a prefix to procedure just to distinct it with system procedures.<br />
Now letâ€™s call our newly created store procedure by using call keyword.<br />
<strong>Call usp_test();<br />
</strong>if you run this from MySQL command line utility you will get something like :</p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun081434.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 08 14.34" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun081434-thumb.gif" border="0" alt="ScreenHunter_01 Jun. 08 14.34" width="558" height="281" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
The procedure we just create is hardly useful, but the basics are there. <em>CREATE PROCEDURE sp_name()</em> will define the procedure, and <em>CALL sp_name()</em> will call the procedure.</p>
<p><strong>Letâ€™s move ahead : Parameters</strong></p>
<p>The real benefit of a stored procedure is when you can pass values to it, as well as retrieve information back. The concept of parameters should be familiar to anyone who has had experience with any procedural programming experience.</p>
<p>There are three types of parameter:</p>
<ul>
<li>IN: The default. This parameter is passed to the procedure, and can change inside the procedure, but remains unchanged outside.</li>
<li>OUT: No value is supplied to the procedure (it is assumed to be NULL), but it can be modified inside the procedure, and is available outside the procedure.</li>
<li>INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the procedure, modified there as well as passed back again.<a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun081730.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 08 17.30" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun081730-thumb.gif" border="0" alt="ScreenHunter_02 Jun. 08 17.30" width="547" height="338" /></a></li>
</ul>
<p><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
<strong>An IN Example:</strong></p>
<p>Here is an example of a stored procedure demonstrating the use of an <em>IN</em> parameter. Since <em>IN</em> is the default, there is no need to specify the parameter as such.</p>
<blockquote>
<pre>mysql&gt; CREATE PROCEDURE USP_IN(p VARCHAR(10)) SET @Name = P;
mysql&gt; CALL USP_IN(â€˜KSHITIJ SHARMAâ€™);
mysql&gt; SELECT @Name;
</pre>
<p>And you should get something like</p></blockquote>
<pre><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun090823.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_01 Jun. 09 08.23" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-01jun090823-thumb.gif" border="0" alt="ScreenHunter_01 Jun. 09 08.23" width="592" height="334" /></a></pre>
<p><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x60_Banner, created 6/9/09 */
google_ad_slot = "7151717024";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
The session variable <em>@Name</em> is set inside of the procedure, based upon the parameter <em>P</em>, which is passed to the procedure, and remains unchanged.</p>
<p><strong>An Out Example:</strong></p>
<p><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun090946.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_02 Jun. 09 09.46" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-02jun090946-thumb.gif" border="0" alt="ScreenHunter_02 Jun. 09 09.46" width="595" height="315" /></a></p>
<p>Here I reset <em>@Name</em> just to make sure the final result is not a legacy of the previous procedure. This time, the parameter <em>P</em> is changed inside of the procedure, while the session variable is passed to the procedure, ready to receive the result.</p>
<p><strong>An In-Out Example:</strong></p>
<pre><a href="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-03jun091110.gif"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="ScreenHunter_03 Jun. 09 11.10" src="http://kshitijsharma.net/wp-content/uploads/2009/06/screenhunter-03jun091110-thumb.gif" border="0" alt="ScreenHunter_03 Jun. 09 11.10" width="617" height="363" /></a></pre>
<p>Here, a parameter is passed to the procedure, used in the calculation, and the results are made available to the session variable <em>@Y.</em></p>
<p><strong>Getting Information from Database :</strong></p>
<blockquote>
<pre>mysql&gt; SHOW PROCEDURE STATUS;mysql&gt; SELECT * FROM INFORMATION_SCHEMA.ROUTINES;<strong></strong></pre>
</blockquote>
<p><strong>Letâ€™s do a bit more complex example :</strong></p>
<p>First, we will create a sample table.</p>
<blockquote>
<pre>mysql&gt; CREATE table tmptest(id INT, txt VARCHAR(10), PRIMARY KEY(id));
Query OK, 0 rows affected (0.11 sec)</pre>
</blockquote>
<p><strong>Delimiters, and multi-statement procedures</strong></p>
<p><div style="display:block; float:right; margin: 0 15px 0 0;"><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 300x250_Medium_Rectangle, created 6/22/09 */
google_ad_slot = "9407728766";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>Stored procedures of course are not that useful if they are just one statement. The effects of all the procedures we have looked at so far could have had been duplicated much more easily with a single SQL statement. Useful procedures are much longer than that. Those of you who are on the ball may be thinking of a complication. How can we differentiate between multiple statements inside the procedure, and the end of the procedure? We have to create a different delimiter to end the CREATE PROCEDURE statement. Here is how:</p>
<blockquote>
<pre>mysql&gt; DELIMITER $$</pre>
</blockquote>
<p>Note that there is no semicolon after the &#8216;$$&#8217; symbol, which we will use as the delimiter for our purposes. You have to choose a delimiter that does not appear in your procedure, and it can be more than one character.</p>
<blockquote>
<pre>mysql&gt; CREATE PROCEDURE usp_ins (P VARCHAR(10))
    -&gt; BEGIN
    -&gt;  SET @x=CHAR_LENGTH(P);
    -&gt;  SET @y = HEX(P);
    -&gt;  INSERT INTO tmptest(id,txt) VALUES(@x,@y);
    -&gt; END$$
Query OK, 0 rows affected (0.05 sec)

mysql&gt; CALL usp_ins('ABC');
    -&gt; $$
Query OK, 1 row affected (0.00 sec)</pre>
</blockquote>
<blockquote>
<pre>mysql&gt; DELIMITER ;
mysql&gt; SELECT * FROM tmptest;
*************************** 1. row ***************************
 id: 3
txt: 414243
1 row in set (0.00 sec)</pre>
</blockquote>
<p><script type="text/javascript"><!--
google_ad_client = "pub-5111267738769255";
/* 468x15_LinkAd_Horizontal, created 6/17/09 */
google_ad_slot = "4303000503";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
Note what happened when we tried to call the procedure. Because MySQL was still using the $$ symbol as a delimiter, and not the semicolon, the statement did not run after the semicolon. We first needed to close it with the piping symbol. Afterwards, we reset the delimiter back to normal, and test that the records were correctly added to the <em>tmptest</em> table.</p>
<p><strong>Procedure Variables:</strong></p>
<p>You can DECLARE variables that exist only inside the procedure, as well as assign values to them with the SET statement without using the &#8216;@&#8217; symbol, required for session variables. Here is how:</p>
<blockquote>
<pre>mysql&gt; DELIMITER $$

mysql&gt; CREATE PROCEDURE usp_variables (P INT)

-&gt; BEGIN</span><span style="font-family: Courier New;">-&gt;Â  DECLARE a INT;
-&gt;Â  DECLARE b INT DEFAULT 10;
-&gt;Â  SET a = P*b;</span><span style="font-family: Courier New;">-&gt;Â  INSERT INTO tmptest(id,txt) VALUES(a,HEX('DEF'));
-&gt; END$$ </span>

<span style="font-family: Courier New;">Query OK, 0 rows affected (0.00 sec) </span>

mysql&gt; DELIMITER ;
mysql&gt; CALL usp_variables(4);
Query OK, 1 row affected (0.00 sec) </span>
mysql&gt; SELECT * FROM tmptest;
*************************** 1. row ***************************
 id: 3
txt: 414243
*************************** 2. row ***************************
 id: 40
txt: 444546
2 rows in set (0.00 sec)</pre>
</blockquote>
<p>if you declare a variable without default (such as a ) it will be set to NULL.</p>
<p><strong>Populating Variables from table.</strong></p>
<blockquote>
<pre>mysql&gt; DELIMITER $$
mysql&gt; CREATE PROCEDURE usp_selectINvariable ()
    -&gt; BEGIN
    -&gt;  DECLARE a INT;
    -&gt;  DECLARE b VARCHAR(10);
    -&gt;  SELECT id,txt INTO a,b FROM tmptest LIMIT 1;
    -&gt;  SELECT a,b;
    -&gt; END|
Query OK, 0 rows affected (0.00 sec)

mysql&gt; DELIMITER ;
mysql&gt; CALL usp_selectINvariable();
*************************** 1. row ***************************
a: 3
b: 414243
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)</pre>
</blockquote>
<p>see how i limit the result to singleÂ  (LIMIT 1)Â  record. In next post i will show you how to iterate multiple records.</p>
<p>I hope you can now write your own store procedure in MySQL.Â  In next post of this series i will show you more complex topics, to show some of the real power of store procedures.</p>
<p><strong>Kshitij</strong></p>
<input id="gwProxy" type="hidden" />
<p><!--Session data--></p>
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<input id="gwProxy" type="hidden" /><!--Session data--><br />
<input id="jsProxy" onclick="jsCall();" type="hidden" />
<div id="st0000000001" class="st-taf"><script src="http://taf.socialtwist.com:80/taf/js/shoppr.core.js?id=0000000001"></script><img style="border:0;margin:0;padding:0;" src="http://tellafriend.socialtwist.com:80/wizard/images/tafbutton_blue16.png" onmouseout="hideHoverMap(this)" onmouseover="showHoverMap(this, '0000000001', 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F09%2Fstored-procedures-in-mysql%2F', 'Stored+Procedures+in+MySQL')" onclick="cw(this, {id:'0000000001',link: 'http%3A%2F%2Fkshitijsharma.net%2F2009%2F06%2F09%2Fstored-procedures-in-mysql%2F', title: '+Stored+Procedures+in+MySQL+' })"/></div>]]></content:encoded>
			<wfw:commentRss>http://kshitijsharma.net/2009/06/09/stored-procedures-in-mysql/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
