Showing posts with label loop. Show all posts
Showing posts with label loop. Show all posts

Tuesday, March 20, 2012

calling another stored procedure within a stored procedure?

Hi, I have a while loop stored procedure, I need to send email for each item in the loop using a sendemail stored procedure. I have two question ..

1) I use EXEC PRODUCTION.DBO.SENDMAIL'email@.hotmail.com', 'Start', 'Job Start' in side the while loop stored procedure, but i didn't get any email or error msg. Why?

2) I try to move a file .. how do I find out if the moving is completed successfully?

-- MOVE FILES
SET @.CMD = 'MOVE /Y ' + '"' + @.ORIGINAL_FILE + '"' + ' "' + @.MOVE_FILE + '"'
EXEC master.dbo.xp_cmdshell @.CMD

Thanks for your reply in advance.

1. I have no idea for the stored procedure SENDMAIL. How did you define it?

2. The xp_cmdshell has only 2 return values: 0 or 1. so you can get the returned value as::

declare @.i bit

EXEC @.i=master.dbo.xp_cmdshell @.CMD

select @.i

Seehttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_xp_aa-sz_4jxo.asp for more information

|||Firstly try changing the email address to one internal to your domain - i had this problem with a system (although i wasnt sending from SQL i was sending from ASP.NET) but the problem ended up being the exchange server security policy not allowing sending to external addresses programatically. You can register the server with the exchange server to allow this i believe but this is something the server team did not me so i could say how to do it.|||Firstly try changing the email address to one internal to your domain - i had this problem with a system (although i wasnt sending from SQL i was sending from ASP.NET) but the problem ended up being the exchange server security policy not allowing sending to external addresses programatically. You can register the server with the exchange server to allow this i believe but this is something the server team did not me so i could not say how to do it.sql

Sunday, March 11, 2012

Calling a SP inside a cursor loop..

I have SP, which has a cursor iterations. Need to call another SP for
every loop iteration of the cursor. The pseudo code is as follows..

Create proc1 as
Begin

Variable declrations...

declare EffectiveDate_Cursor cursor for
select field1,fld2 from tab1,tab2 where tab1.effectivedate<Getdate()
--/////Assuming the above query would result in 3 records
Open EffectiveDate_Cursor
Fetch next From EffectiveDate_Cursor Into @.FLD1,@.FLD2
begin
/*Calling my second stored proc with fld1 as a In parameter
and Op1 and OP2 Out parameters*/
Exec sp_minCheck @.fld1, @.OP1 output,@.OP2 output
Do something based on Op1 and Op2.
end
While @.@.Fetch_Status = 0
Fetch next From EffectiveDate_Cursor Into @.FLD1,@.FLD2
/* Assume If loop count is 3.
and If the Fetch stmt is below the begin Stmt, the loop iterations are
4 else the loop iterations are 2*/
begin
/*Calling my second stored proc with fld1 as a In parameter and Op1
and OP2 Out parameters*/
Exec sp_minCheck @.fld1, @.OP1 output,@.OP2 output
Do something based on Op1 and Op2.
end

The problem I had been facing is that, the when a stored proc is called
within the loop, the proc is getting into infinite loops.
Any Help would be appreciated.

Satish(satishchandra999@.gmail.com) writes:
> I have SP, which has a cursor iterations. Need to call another SP for
> every loop iteration of the cursor. The pseudo code is as follows..
> Create proc1 as
> Begin
> Variable declrations...
>...
> While @.@.Fetch_Status = 0
> Fetch next From EffectiveDate_Cursor Into @.FLD1,@.FLD2
> /* Assume If loop count is 3.
> and If the Fetch stmt is below the begin Stmt, the loop iterations are
> 4 else the loop iterations are 2*/
> begin
> /*Calling my second stored proc with fld1 as a In parameter and Op1
> and OP2 Out parameters*/
> Exec sp_minCheck @.fld1, @.OP1 output,@.OP2 output
> Do something based on Op1 and Op2.
> end
>
> The problem I had been facing is that, the when a stored proc is called
> within the loop, the proc is getting into infinite loops.

May I guess: the inner process also uses cursors?

Anyway, the proper way to program a cursor loop is:

DECLARE cur INENSITIVE CURSOR FOR
SELECT ...
-- Error handling goes here

OPEN cur

WHILE 1 = 1
BEGIN
FETCH cur INTO @.x, @.y, ...
IF @.@.fetch_status <> 0
BREAK

-- Do stuff
END

DEALLOCATE cur

By using only one FETCH statements you avoid funny errors, when you change
the cursor and forgets to change the cursor at the end of the loop. And by
checl @.@.fetch_status directly after the FETCH, you know that @.@.fetch_status
relates to that FETCH.

... and in case no one ever told you before: avoid iterations as much as
you can, and try to always work set-based. Yes, I can understand that you
want to reuse code, and if the oomplexity is high enough it may be
warranted if the number of rows in the cursor is moderate. But the cost
in performance for iterative solutions can be *enourmous*. A database
engine is simply not designed for this type of processing.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||>> I have SP, which has a cursor iterations. Need to call another SP for
every loop iteration of the cursor. <<

No. You need to learn to program in SQL. All you are doing is
mimicing a 1960's 3GL magnetic tape file system . In your pseudo
code, you even refer to fields instead of columns! You put the "sp_"
prefix on procedure names!

Don't you understand that SQL is a non-procedurdal language? You
should write only a few cursors in 20 years, not two in one
application.

Your whole approach to the problem is **fundamentally** wrong.

>> The problem I had been facing is that, the when a stored proc is called within the loop, the proc is getting into infinite loops. <<

It is very hard to de-bug code that you will not show us. But when
pseudo code is this awful, I bet that the real code is a total mess.
More cursors? Dynamic SQL? Badly written procedural code with poor
coupling and cohesion?

>> Any Help would be appreciated. <<

You have no idea what you are doing. What you will get on Newsgroups
is a quick kludge to get rid of you, but not any real help. You need
to stop programming and get some education; then get some training.

Calling a Stored Procedure from inside of a loop..

Hello,
I know calling a stored procedure from inside of loop is something that
we all want to aviod, and the most of times there's a better
alternative.
However, I am afraid this is one of the few exceptions that I really
have to call a stored procedure from inside of loop. Just in case you
wonder why, there is a stored procedure which takes one parameter,
namely member_ID, and I would like to test it out against about 12,000
rows in the members table.
So, basically I would like to call this stored procedures about 12,000
times, each time with a different member ID, just to make sure the
stored procedure works for each member.
I know it kinda sound really anal, but because of the complexity of the
stored procedure, mainly due to the poor database design done in years
ago (or so I blame :), despite the fact it only receives one paramter,
there have been instances that the stored procedure did not return a
row for a certain group of members.
I've been working on the stored procedure to make it handel some of
those "special" situations, so that it always returns a row, even if it
is populated with some crooked values. Now I think I've finished
taking care of all that... but, I will definitely sleep better if I can
test it out. So, here I am.
There is a While Loop in TSQL that seems like the one I should use for
this task, but the problem I am having is how to call my stored
procedure with a different member ID in each iteration.
Please remember that, for this particular situation altering the stored
procedure to query a table of member ID's instead of a single member ID
is not an option. Again, because of the complexity of the problem I
need to solve, I was not able to squeeze the query into a single Select
statement in my procedure. It contains a number of calculations, which
use different set of parameters depending on the group the member
belongs to...
Yes, this probably wasn't good idea to do all this conditional
calculations in the stored procedure, but that is how our application
works - probably a really bad design, of course which wasn't done by me
:)
All in all, it's too late to make any kind of architectural changes at
this point, and I am stuck with a task that I have to write a stored
procedure that does all the wonders and returns a row when called with
a single parameter, member ID, no matter how inefficient and slow it
gets.
Since I am trying to do this exhaustive testing for my own sake and on
my own, using a small test code outside of the database using a more
suitable programming language isn't going to be easy, either.
In other words, I need to call my stored procedure which takes one
parameter within a loop with supplying a different parameter each time,
and I need to do this in TSQL.
Thank you very much for your help in advance!Consider these options as well, if they fit your needs:
1) a user-defined function that gets called 12K times while executing a
query inside a stored proc, e.g.
SELECT MemberId, dbo.DoMembersCalc(member_ID) as CalculatedMemberValue
FROM Members
2) a calculated column
SELECT MemberId, CalculatedMemberValue
FROM Members
3) a view
SELECT MemberId, CalculatedMemberValue
FROM MemberView
You can subquery any of these statements to see if any particular
MemberId had an undesireable result in the CalculatedMemberValue
column.
jung_h_park@.yahoo.com wrote:
> Hello,
> I know calling a stored procedure from inside of loop is something that
> we all want to aviod, and the most of times there's a better
> alternative.
> However, I am afraid this is one of the few exceptions that I really
> have to call a stored procedure from inside of loop. Just in case you
> wonder why, there is a stored procedure which takes one parameter,
> namely member_ID, and I would like to test it out against about 12,000
> rows in the members table.
> So, basically I would like to call this stored procedures about 12,000
> times, each time with a different member ID, just to make sure the
> stored procedure works for each member.
> I know it kinda sound really anal, but because of the complexity of the
> stored procedure, mainly due to the poor database design done in years
> ago (or so I blame :), despite the fact it only receives one paramter,
> there have been instances that the stored procedure did not return a
> row for a certain group of members.
> I've been working on the stored procedure to make it handel some of
> those "special" situations, so that it always returns a row, even if it
> is populated with some crooked values. Now I think I've finished
> taking care of all that... but, I will definitely sleep better if I can
> test it out. So, here I am.
> There is a While Loop in TSQL that seems like the one I should use for
> this task, but the problem I am having is how to call my stored
> procedure with a different member ID in each iteration.
> Please remember that, for this particular situation altering the stored
> procedure to query a table of member ID's instead of a single member ID
> is not an option. Again, because of the complexity of the problem I
> need to solve, I was not able to squeeze the query into a single Select
> statement in my procedure. It contains a number of calculations, which
> use different set of parameters depending on the group the member
> belongs to...
> Yes, this probably wasn't good idea to do all this conditional
> calculations in the stored procedure, but that is how our application
> works - probably a really bad design, of course which wasn't done by me
> :)
> All in all, it's too late to make any kind of architectural changes at
> this point, and I am stuck with a task that I have to write a stored
> procedure that does all the wonders and returns a row when called with
> a single parameter, member ID, no matter how inefficient and slow it
> gets.
> Since I am trying to do this exhaustive testing for my own sake and on
> my own, using a small test code outside of the database using a more
> suitable programming language isn't going to be easy, either.
> In other words, I need to call my stored procedure which takes one
> parameter within a loop with supplying a different parameter each time,
> and I need to do this in TSQL.
> Thank you very much for your help in advance!|||For this sort of testing scenario, a cursor is a perfectly viable
option (of course, that goes with the usual disclaimer about avoiding
cursors in production code, they are inherently evil, and bad things
will happen to you if you forsake this advice, don't get them wet, and
never ever feed them after midnight....).
Look up cursors in the Books Online. and that should get you pointed in
the right direction.
HTH,
Stu
jung_h_park@.yahoo.com wrote:
> Hello,
> I know calling a stored procedure from inside of loop is something that
> we all want to aviod, and the most of times there's a better
> alternative.
> However, I am afraid this is one of the few exceptions that I really
> have to call a stored procedure from inside of loop. Just in case you
> wonder why, there is a stored procedure which takes one parameter,
> namely member_ID, and I would like to test it out against about 12,000
> rows in the members table.
> So, basically I would like to call this stored procedures about 12,000
> times, each time with a different member ID, just to make sure the
> stored procedure works for each member.
> I know it kinda sound really anal, but because of the complexity of the
> stored procedure, mainly due to the poor database design done in years
> ago (or so I blame :), despite the fact it only receives one paramter,
> there have been instances that the stored procedure did not return a
> row for a certain group of members.
> I've been working on the stored procedure to make it handel some of
> those "special" situations, so that it always returns a row, even if it
> is populated with some crooked values. Now I think I've finished
> taking care of all that... but, I will definitely sleep better if I can
> test it out. So, here I am.
> There is a While Loop in TSQL that seems like the one I should use for
> this task, but the problem I am having is how to call my stored
> procedure with a different member ID in each iteration.
> Please remember that, for this particular situation altering the stored
> procedure to query a table of member ID's instead of a single member ID
> is not an option. Again, because of the complexity of the problem I
> need to solve, I was not able to squeeze the query into a single Select
> statement in my procedure. It contains a number of calculations, which
> use different set of parameters depending on the group the member
> belongs to...
> Yes, this probably wasn't good idea to do all this conditional
> calculations in the stored procedure, but that is how our application
> works - probably a really bad design, of course which wasn't done by me
> :)
> All in all, it's too late to make any kind of architectural changes at
> this point, and I am stuck with a task that I have to write a stored
> procedure that does all the wonders and returns a row when called with
> a single parameter, member ID, no matter how inefficient and slow it
> gets.
> Since I am trying to do this exhaustive testing for my own sake and on
> my own, using a small test code outside of the database using a more
> suitable programming language isn't going to be easy, either.
> In other words, I need to call my stored procedure which takes one
> parameter within a loop with supplying a different parameter each time,
> and I need to do this in TSQL.
> Thank you very much for your help in advance!

Thursday, March 8, 2012

Call stored procedure in loop

I have gridview display a list of users. I have added a column for a check box. If the box is checked I move the users to another table.

I need to pass some parameter of or each row to a stored proc.

My question.

In the loop where I check if the checkbox is selected I need to call the stored procedure.

Currently I do an open and closed inside the loop.

What is best and most effficent method of doing this should I open and close the connection outside the loop and change the procs parameters as loop through.

 System.Data.SqlClient.SqlConnection conn =new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connString"].ConnectionString); System.Data.SqlClient.SqlCommand commChk =new System.Data.SqlClient.SqlCommand("storedProc", conn); commChk.CommandType = System.Data.CommandType.StoredProcedure; commChk.Parameters.AddWithValue("@.mUID", ddMainUser.SelectedValue.ToString()); commChk.Parameters.AddWithValue("@.sUId", gvUsers.Rows[i].Cells[2].Text); commChk.Connection.Open(); commChk.ExecuteNonQuery(); conn.Close();

If so exactly how do I do this? How do I reset the parmaters for the proc?

I haven't done this before where I need to loop through passing parameter to the same proc.

thanks

If you are going to reuse the same SqlCommand object several times, you should call

commChk.Parameters.Clear();

to clear out the contents of the parameter collection before adding new values.

Hope this helps.

|||

I would do it like this:

build connection object

build command object (assigning the command to the connection)

Build command parameters w/ datatype.

open connection

begin loop

set command parameter values

execute command

end loop

close connection

in vb it would be:

Dim conn as new sqlconnection(ConfigurationManger...)

dim cmd as new sqlcommand("SELECT ...",conn)

cmd.Parameters.Add("@.param1",sqldbtype.int)

cmd.Parameters.Add("@.param2",sqldbtype.varchar)

conn.open

while ...

cmd.Parameters("@.param1").value= ...

cmd.Parameters("@.param2").value= ...

cmd.executenonquery

end while

conn.close

--

Notice very little actually takes place within the loop. I'm not creating whole objects, or creating connections, just setting a few values and executing the command. It also makes it easier to wrap up in a nice catch/try block or a transaction.