473,699 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

First attempt at Stored Procedure - can anyone offer advice

aaj
SQL SERVER 2000

Hi all

This is my first attempt at writing a stored procedure. I have managed to
get it working but its unlikely to be the best way of handling the problem.
While writing it I found some things that I don't understand so if any one
could shed any light it would be much appreciated. I have posted these at
the end.

Sorry about the length but I thought it might be worthwhile posting the code

The purpose of the procedures is as follows : we have a view of lots of bits
of information that need automatically mailing to different people. each
element of information has a name allocated against it. If we had 100 pieces
of data, 50 could go to manager 1 25 could go to manager 2 and 25 to manager
3 etc...

Both SP's look at the same view

The first SP generates a distinct list of managers and for each manager
calls the second SP

The second SP filters the view for the data belonging to the selected
manager, and builds an HTML mail. It then sends all the bits of information
belonging to that manager off in an EMAIL to him/her. ( It uses a brilliant
bit of code from sqldev.net to handle the mail)

the first mail then repeats for all the managers in the list

CODE ---- SP 1
ALTER PROCEDURE dbo.PR_ADMIN_CL IENT_WEEKLY_NOT IFICATION_2
AS
begin
SET NOCOUNT ON
declare @no_of_managers as int
declare @current_record as int
declare @manager_name as varchar(100)

-- count how many distinct managers we need to send the mail to
select @no_of_managers = COUNT(DISTINCT manager_name) FROM
dbo.vw_client_n otification_ema il_1

-- open a cursor to the same distinct list
declare email_list cursor for select distinct manager_name from
dbo.vw_client_n otification_ema il_1 dsc
open email_list

-- for each distinct manager get the managers name and pass it to the stored
procedure that generates the mail.
set @current_record = 0
while (@current_recor d) < @no_of_managers
begin
fetch next from email_list into @manager_name
EXECUTE dbo.pr_admin_cl ient_weekly_not ification @manager_name
set @current_record = @current_record +1
end
-- close the cursor
close email_list
deallocate email_list
end

CODE ---- SP2
ALTER PROCEDURE dbo.PR_ADMIN_CL IENT_WEEKLY_NOT IFICATION
(@current_manag er_name as varchar(100))
-- a unique managers name is passed from the calling procedure
as begin
SET NOCOUNT ON
-- declarations for use in the stored procedure
DECLARE @to as varchar(100)
DECLARE @entry varchar(500)
DECLARE @region as varchar(100)
DECLARE @type as varchar(100)
DECLARE @site_ref as varchar(100)
DECLARE @aborted as varchar(100)
DECLARE @weblink as varchar(1000)
DECLARE @manager_name as varchar(100)
DECLARE @manager_email as varchar(100)
DECLARE @body VARCHAR(8000)
DECLARE @link varchar(150)
DECLARE @web_base VARCHAR(150)

-- set up a connection to the view that contains the details for the mail

DECLARE email_contents cursor for select region,type,
site_ref,aborte d_visit,link,ma nager_name,mana ger_email from
vw_client_notif ication_email_1 where manager_name = @current_manage r_name
open email_contents
--some initial text
set @body = '<font color="#FF8040" ><b>Reports W/E ' +convert(char(5 0),
getdate()) + '</b></font><br><br> <a href = http://xxxx > Click here to log
on to xxxxx </a><br><br> '
--fetch the first matching record from the table and build the body of the
message
fetch next from email_contents into
@region,@type,@ site_ref,@abort ed,@link,@manag er_name,@manage r_email
set @web_base = 'http://'
set @weblink = @web_base + @link
if @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'
set @body = @body + '<font size="2"><b> Region </b>' + @region
+ ' <b>Type</b> ' + @type
+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+
'</a>'
+ ' <b>Unique Report Reference </b>' + @link + '<br>'

-- continue reading the records for this particular message and adding on to
the body of the text
while(@@fetch_s tatus = 0)
begin
fetch next from email_contents into
@region,@type,@ site_ref,@abort ed,@link,@manag er_name,@manage r_email
if @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'
if (@@fetch_status = 0) set @body = @body + '<b> Region </b>' + @region
+ ' <b>Type</b> ' + @type
+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+
'</a>'
+ '<b>Unique Report Reference </b>' + @link + '<br>'
end

-- close the cursor
set @body = @body + '</font>'
close email_contents
deallocate email_contents
-- generate the mail
DECLARE @rc int EXEC @rc = master.dbo.xp_s mtp_sendmail
@FROM = N'FROM ME',
@TO = @manager_email,
@server = N'server',
@subject = N'Weekly Import',
@message = @body,
@type = N'text/html'
end


Questions

is the way I've done it OK. I thought I would be able to do it in a single
SP but I really struggled nesting the cursor things.

@@fetchstatus seems to be global, so if your using nested cursors, how do
you know which one you are refering to. If you have multiple calls to the
same SP how does it know which instance of the SP it refers to.

When I first wrote it, I used a cursor in SP1 to call SP2, but I couldn't
get the while loop working - I have a feeling it was down to the @@
fetchstatus in the 'calling' procedure being overwritten by the
@@fetchstatus in the 'called' procedure.

The whole @@fetchatus thing seems a bit odd. In the second procedure, I have
to fetch, then check, manipulate then fetch again, meaning that the same
manipulation code is written twice. thats why in the first procedure I used
the select distint count to know how long the record set is so I only have
to run the manipulation code once. Is what I have done wrong?

its possible that the body of the mail could be > 8K, is there another
datatype I can use to hold more than 8K
many thanks for any help or advice

Andy

Jul 20 '05 #1
3 4013

"aaj" <a.*@c.com> wrote in message
news:40******** *************** @news.easynet.c o.uk...
SQL SERVER 2000

Hi all

This is my first attempt at writing a stored procedure. I have managed to
get it working but its unlikely to be the best way of handling the problem. While writing it I found some things that I don't understand so if any one
could shed any light it would be much appreciated. I have posted these at
the end.

Sorry about the length but I thought it might be worthwhile posting the code
<snip>
Questions

is the way I've done it OK. I thought I would be able to do it in a single
SP but I really struggled nesting the cursor things.

@@fetchstatus seems to be global, so if your using nested cursors, how do
you know which one you are refering to. If you have multiple calls to the
same SP how does it know which instance of the SP it refers to.

When I first wrote it, I used a cursor in SP1 to call SP2, but I couldn't
get the while loop working - I have a feeling it was down to the @@
fetchstatus in the 'calling' procedure being overwritten by the
@@fetchstatus in the 'called' procedure.

The whole @@fetchatus thing seems a bit odd. In the second procedure, I have to fetch, then check, manipulate then fetch again, meaning that the same
manipulation code is written twice. thats why in the first procedure I used the select distint count to know how long the record set is so I only have
to run the manipulation code once. Is what I have done wrong?

its possible that the body of the mail could be > 8K, is there another
datatype I can use to hold more than 8K
many thanks for any help or advice

Andy


I must admit I didn't read your code in detail, but I'm not sure why you
need two procedures. The inner one appears to go through every row in
dbo.vw_client_n otification_ema il_1, so I don't see the benefit of the outer
one (unless perhaps you removed some code to simplify it). Also, the outer
procedure seems to use a counter to find the end of the cursor, but
@@FETCH_STATUS will tell you when you have reached the end of the cursor
anyway.

As for the data type, there are larger data types available (text and
ntext), but xp_smtp_sendmai l doesn't support them. If you need to send large
emails, I would consider using an external script instead of pure SQL code -
it's much easier to create attachment files, do text/HTML formatting and
validation etc.If you want to keep control within a procedure, then you
could use xp_cmdshell to call your script, or perhaps just schedule it as a
SQL Agent job.

Simon
Jul 20 '05 #2
aaj (a.*@c.com) writes:
is the way I've done it OK. I thought I would be able to do it in a single
SP but I really struggled nesting the cursor things.
It could be done in a single SP, but splitting it in two has the
advantage that you don't risk that the value of some variable spill
over from the previous manager.

You could also do it with one cursor only. In this case you would
have something like:

IF @old_manager IS NOT NULL AND @manager <> @old_manager
BEGIN
EXEC master.dbo.xp_s endmail ....
-- Reset all variables.
SELECT @old_manager = @manager
END

You could of course have to order the cursor by manager.
@@fetchstatus seems to be global, so if your using nested cursors, how do
you know which one you are refering to. If you have multiple calls to the
same SP how does it know which instance of the SP it refers to.


@@fetch_status refers to the cursor you last operated on. And if you
check @@fetch_status directly after FETCH you are safe. Here is the
idiom for writing a cursor loop:

DECLARE some_cur INSENSITIVE CURSOR FOR
SELECT yadayada

OPEN some_cur

WHILE 1 = 1
BEGIN
FETCH some_cur INTO ...
IF @@fetch_status <> 0
BREAK
...
END

DEALLOCATE some_cur

The INSENSITIVE is there, because the default keyset-driven cursors can
sometimes come with nasty suprises.

By only using one FETCH statement your code is easier to maintain; if you
need another column in the cursor, you only have to change in two places.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #3
aaj
Thanks chaps

I'll have a read in detail and see if I can pick up some tips
Andy

"aaj" <a.*@c.com> wrote in message
news:40******** *************** @news.easynet.c o.uk...
SQL SERVER 2000

Hi all

This is my first attempt at writing a stored procedure. I have managed to
get it working but its unlikely to be the best way of handling the problem. While writing it I found some things that I don't understand so if any one
could shed any light it would be much appreciated. I have posted these at
the end.

Sorry about the length but I thought it might be worthwhile posting the code
The purpose of the procedures is as follows : we have a view of lots of bits of information that need automatically mailing to different people. each
element of information has a name allocated against it. If we had 100 pieces of data, 50 could go to manager 1 25 could go to manager 2 and 25 to manager 3 etc...

Both SP's look at the same view

The first SP generates a distinct list of managers and for each manager
calls the second SP

The second SP filters the view for the data belonging to the selected
manager, and builds an HTML mail. It then sends all the bits of information belonging to that manager off in an EMAIL to him/her. ( It uses a brilliant bit of code from sqldev.net to handle the mail)

the first mail then repeats for all the managers in the list

CODE ---- SP 1
ALTER PROCEDURE dbo.PR_ADMIN_CL IENT_WEEKLY_NOT IFICATION_2
AS
begin
SET NOCOUNT ON
declare @no_of_managers as int
declare @current_record as int
declare @manager_name as varchar(100)

-- count how many distinct managers we need to send the mail to
select @no_of_managers = COUNT(DISTINCT manager_name) FROM
dbo.vw_client_n otification_ema il_1

-- open a cursor to the same distinct list
declare email_list cursor for select distinct manager_name from
dbo.vw_client_n otification_ema il_1 dsc
open email_list

-- for each distinct manager get the managers name and pass it to the stored procedure that generates the mail.
set @current_record = 0
while (@current_recor d) < @no_of_managers
begin
fetch next from email_list into @manager_name
EXECUTE dbo.pr_admin_cl ient_weekly_not ification @manager_name
set @current_record = @current_record +1
end
-- close the cursor
close email_list
deallocate email_list
end

CODE ---- SP2
ALTER PROCEDURE dbo.PR_ADMIN_CL IENT_WEEKLY_NOT IFICATION
(@current_manag er_name as varchar(100))
-- a unique managers name is passed from the calling procedure
as begin
SET NOCOUNT ON
-- declarations for use in the stored procedure
DECLARE @to as varchar(100)
DECLARE @entry varchar(500)
DECLARE @region as varchar(100)
DECLARE @type as varchar(100)
DECLARE @site_ref as varchar(100)
DECLARE @aborted as varchar(100)
DECLARE @weblink as varchar(1000)
DECLARE @manager_name as varchar(100)
DECLARE @manager_email as varchar(100)
DECLARE @body VARCHAR(8000)
DECLARE @link varchar(150)
DECLARE @web_base VARCHAR(150)

-- set up a connection to the view that contains the details for the mail

DECLARE email_contents cursor for select region,type,
site_ref,aborte d_visit,link,ma nager_name,mana ger_email from
vw_client_notif ication_email_1 where manager_name = @current_manage r_name
open email_contents
--some initial text
set @body = '<font color="#FF8040" ><b>Reports W/E ' +convert(char(5 0),
getdate()) + '</b></font><br><br> <a href = http://xxxx > Click here to log on to xxxxx </a><br><br> '
--fetch the first matching record from the table and build the body of the
message
fetch next from email_contents into
@region,@type,@ site_ref,@abort ed,@link,@manag er_name,@manage r_email
set @web_base = 'http://'
set @weblink = @web_base + @link
if @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'
set @body = @body + '<font size="2"><b> Region </b>' + @region
+ ' <b>Type</b> ' + @type
+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+
'</a>'
+ ' <b>Unique Report Reference </b>' + @link + '<br>'

-- continue reading the records for this particular message and adding on to the body of the text
while(@@fetch_s tatus = 0)
begin
fetch next from email_contents into
@region,@type,@ site_ref,@abort ed,@link,@manag er_name,@manage r_email
if @aborted = 0 set @aborted = '' else set @aborted = 'ABORTED'
if (@@fetch_status = 0) set @body = @body + '<b> Region </b>' + @region
+ ' <b>Type</b> ' + @type
+ ' <b>Site Reference </b> <a href = "' + @weblink + '">' + @site_ref+
'</a>'
+ '<b>Unique Report Reference </b>' + @link + '<br>'
end

-- close the cursor
set @body = @body + '</font>'
close email_contents
deallocate email_contents
-- generate the mail
DECLARE @rc int EXEC @rc = master.dbo.xp_s mtp_sendmail
@FROM = N'FROM ME',
@TO = @manager_email,
@server = N'server',
@subject = N'Weekly Import',
@message = @body,
@type = N'text/html'
end


Questions

is the way I've done it OK. I thought I would be able to do it in a single
SP but I really struggled nesting the cursor things.

@@fetchstatus seems to be global, so if your using nested cursors, how do
you know which one you are refering to. If you have multiple calls to the
same SP how does it know which instance of the SP it refers to.

When I first wrote it, I used a cursor in SP1 to call SP2, but I couldn't
get the while loop working - I have a feeling it was down to the @@
fetchstatus in the 'calling' procedure being overwritten by the
@@fetchstatus in the 'called' procedure.

The whole @@fetchatus thing seems a bit odd. In the second procedure, I have to fetch, then check, manipulate then fetch again, meaning that the same
manipulation code is written twice. thats why in the first procedure I used the select distint count to know how long the record set is so I only have
to run the manipulation code once. Is what I have done wrong?

its possible that the body of the mail could be > 8K, is there another
datatype I can use to hold more than 8K
many thanks for any help or advice

Andy

Jul 20 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1665
by: Martin Feuersteiner | last post by:
Dear Group I have found that table A had SELECT permissions for 'Public' but not table B. Giving 'Public' SELECT permissions on table B did the trick. HOWEVER, I don't want anyone to be able to do a direct SELECT on table A or B but only give them access to the data by using the stored procedures. Is there any way this can be set up?
3
2380
by: Bruce | last post by:
Since DBlib is no longer the suggested method for connecting back to sql server from an Extended Stored Procedure, has anyone built any extended stored procedures that use other connection methods like OLEDB? Has anyone seen links to any sample extended stored procedures that use something other than db-lib? In particular I am interested in something that connects back to the database as the user who invoked the extended stored...
3
1656
by: 8leggeddj | last post by:
Hello, I am having a problem when using access xp as a frontend for sql server 2000. I have been trying to update a number of stored procedures (Just simple adding fields etc) which results in access crashing with event ID 1000 and 1001. Does anyone have any ideas as to what could be the problem? Thanks in advance..
13
10438
by: dawatson833 | last post by:
I have several stored procedures with parameters that are defined with user defined data types. The time it takes to run the procedures can take 10 - 50 seconds depending on the procedure. If I change the parameter data types to the actual data type such as varchar(10), etc., the stored procedure takes less that a second to return records. The user defined types are mostly varchar, but some others such as int. They are all input type...
1
7344
by: Private Pyle | last post by:
DB2 version 8, fixpack 5. Aix 5.1.0.0 Using C for AIX compiler. I'm having a problem where I can create stored procedures but I'm getting -444 when I call them. It's a new environment for running SP's so I wrote a very simple procedure just to make sure everything is working. Below is the db2set output for the SQLROUTINE_COMPILE_COMMAND, stored procedure text, log file, and result of a call. I'm getting an error that says function...
10
3557
by: Eric E | last post by:
Hi all, I am using an Access client linked to a PG 7.4 server via ODBC. I have a stored proc on the server that inserts rows into a table.particular table, accomplished via an INSERT within the body of the stored proc. The procedure does not explicitly commit this data, as no transactions are invoked. The problem is that Access will not modify these records via table or form view, giving its generic "Write conflict: another user has...
2
6118
by: bshumsky06 | last post by:
Hi, I am trying to create stored procedures in MySQL. Does anyone have a suggestion on a good IDE to use. I have been working with the MySQL Query Browser but it generates errors very often and is shut down by Windows. When I make changes to my procedure, it doesn't seem to always change what is being executed. Furthermore, sometimes the procedure just disappears from my database. I am starting to think that the stored procedure...
0
3488
by: istruttorenuoto | last post by:
hi! I have some problems to call a stored procedure from an Unix Script. Here's the script stty istrip stty erase ^H export ORACLE_BASE=/product/oracle export ORACLE_HOME=$ORACLE_BASE/product/9.2.6 export PATH=$ORACLE_HOME/bin:/usr/ccs/bin:/bin:/usr/bin:/usr/local/bin:/usr/ucb
4
3136
by: PJackson | last post by:
I have been given the task of taking a 3,200 line COBOL stored procedure and duplicating the same functionality in UDB 7.2 on the Windows platform with a procedural SQL stored procedure. I have fiddled with procedural SQL stored procs on UDB, but mostly short,trivial ones. Looking for good advice, links, etc. on the best approach to this. There doesn't seem to be the concept of subroutines within a stored proc, so I am guessing one main...
0
8703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8623
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9050
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6540
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4389
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.