Cursor In Sproc To Kill Spids Loops Forever

Mar 20, 2000

I need a stored proc to kill spids, but the following sproc loops infinitely with the same [correct] spid being printed out. What am I doing wrong?

The select statement, when I execute it via the query grid, returns the correct and finite number of spids.

Any help greatly appreciated.
Judith


CREATE PROCEDURE rasp_KillDBProcess
@dbname varchar(128)
AS
declare @KillSpid smallint
declare @SQL varchar(1000)
--
declare DBCursor cursor Forward_only for SELECT distinct l.spid
FROM master.dbo.syslocks l INNER JOIN
master.dbo.sysdatabases d ON l.dbid = d.dbid
WHERE (d.name = N'coj_pcisdata')
open DBCursor
--
Fetch next from DBCursor into @Killspid
--
While (@@Fetch_status <> -1)
Begin
If (@@Fetch_status <> -2)
begin
print 'spid = ' + cast(@killspid as varchar(12))
--exec ('kill ' + @killspid)

end
--
end
Fetch next from DBCursor into @Killspid
--
close dbcursor
deallocate dbcursor
print 'end'

return

View 1 Replies


ADVERTISEMENT

Cursor Vs Loops

Feb 21, 2008

Hello all.
I'm mostly a VB.Net developer. I've been working on a intranet app that allows poeple in our company to self regisiter for access to Tools/Systems.

The data stucture: 1 Request with many Users requesting access.. Also on the same request, many applications requested for those same people.

After the application routes some 'Manager Reviews' and Updated the tblRequest, approving the request, I combine the Information into a tblRegistrations.

So there is a Matrix created.
The Users requested are (User1, User2, UserX....)
The Apps requested are (App1, App2, Appx....)

I created a Stored Proc that reads the List of USers, and inserts a record into tblRegistered for each App that was requested.
User1, App1
User1, App2
User1, App3
User1, Appx
User2, App1
User2, App2
User2, App3
User2, AppX
UserX, AppX
...., ....

I user 2 cursors, Nested.
The outer Cursor is the List of Users, and the inner Cusros is the list apps.

I appreciate if somone can show me how to do this with some other looping structure, or if not, examine the Decalrative statement of the Cursor, and define the propteries to make it most efficient, ie Static Local Forward Only, ect.

As I said, I don't DB Developer Experience.

Below is the copy of the Working Stored Proc:

ALTER PROCEDURE [dbo].[sp_Insert_Registration]
-- Add the parameters for the stored procedure here
@Request_IDINT
,@SessionIDnvarchar(150)

AS

DECLARE @Request_user_FullName nvarchar(150)
DECLARE @Request_User_IonName nvarchar(150)
DECLARE @Request_App_ID INT
DECLARE @Request_App_Role nvarchar(50)
DECLARE @Reg_Date DateTime

BEGIN TRY


--Local Scalar Values
Select @Reg_Date=Request_Date From dbo.tblRequest Where Request_ID=@Request_ID


--First Cursor

DECLARE curRequest_Users CURSOR LOCAL STATIC FOR
SELECT Request_User_FullName, Request_User_IonName
From dbo.tblRequest_Users
Where Request_ID =@Request_ID AND request_User_Session_ID=@SessionID

Open curRequest_Users


--Second Cursor

DECLARE curRequest_Applications CURSOR LOCAL Static FOR
SELECT Request_App_ID, Request_App_Role
From dbo.tblRequest_Applications
Where Request_ID =@Request_ID
AND Request_Apps_SessionID=@SessionID

FETCH curRequest_Users INTO @Request_user_FullName, @Request_User_IonName
WHILE @@FETCH_STATUS = 0
BEGIN
--Insert the Row Into tblRegistrations
--Need to get the Application ID's the User(s) Has Been Approved For

Open curRequest_Applications


FETCH curRequest_Applications INTO @Request_App_ID, @Request_App_Role
WHILE @@FETCH_STATUS = 0
BEGIN
Insert Into dbo.tblRegistrations
(Request_ID
,FUllName
,IonName
,Application_ID
,Application_Role
,Reg_Date
,Approved
,Approval_Date
)
Values (
@Request_ID
,@Request_user_FullName
,@Request_User_IonName
,@Request_App_ID
,@Request_App_Role
,@Reg_Date
,'True'
,getdate()
)
FETCH curRequest_Applications INTO @Request_App_ID, @Request_App_Role

END
--Close the Inner Cursor
CLOSE curRequest_Applications

FETCH curRequest_Users INTO @Request_user_FullName, @Request_User_IonName

END




DEALLOCATE curRequest_Applications

CLOSE curRequest_Users
DEALLOCATE curRequest_Users


END TRY
BEGIN CATCH
-- Execute error retrieval routine.
EXECUTE usp_GetErrorInfo;

END CATCH;

View 2 Replies View Related

How Do I Kill Off An Old Cursor In Memory

Apr 18, 2006

there is a sproc with cursors . occasionally the sproc fails before the cursors can be deallocated. when i try to deallocate the cursor manually im told it doesnt exist, even though i can clearly see it when i go to :



select * from sys.dm_exec_cursors(0)



how do i kill off my cursor that isnt being used??

View 1 Replies View Related

Logic Problem In Cursor/SPROC

Jul 23, 2005

SQL Server 2000I have a stored procedure that uses an extended SPROC to send an emailnotification to my customers when a document is distributed.However, the SPROC has an unexpected side effect.If I run it in its current incarnation, it only sends one email andthen exits. However, if I remove or comment out the block/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)then it runs through the whole list as anticipated. Conceptually, itseems that the records in the cursor are changed if the underlyingtable is updated.Here is pseudo-code for what the SPROC does - whole SPROC below (withpart of the "WHERE" clause removed for readability). I haven'tincluded any table schemae but I don't think they're relevant.1. Open a cursor and fetch a list of all companies that need emailnotification for pending jobs.2. While records in the cursor...a) Format and send email from the cursorb) Write a record to the audit tablec) Update the jobs table for the current record3) Fetch next from cursorThere is an update trigger on the tblJobs table thus:CREATE TRIGGER "tblJobs_UTrig" ON dbo.tblJobs FOR UPDATE ASSET NOCOUNT ON/* * PREVENT UPDATES IF NO MATCHING KEY IN 'tblDistributionMaster' */IF UPDATE(fldDistributionID)BEGINIF (SELECT COUNT(*) FROM inserted) !=(SELECT COUNT(*) FROM tblDistributionMaster, inserted WHERE(tblDistributionMaster.fldDistributionID = inserted.fldDistributionID))BEGINRAISERROR 44446 'The record can''t be added or changed.Referential integrity rules require a related record in table''tblDistributionMaster''.'ROLLBACK TRANSACTIONENDEND/* * PREVENT UPDATES IF DEPENDENT RECORDS IN 'tblPrinterJobs' */IF UPDATE(fldJobID)BEGINIF (SELECT COUNT(*) FROM deleted, tblPrinterJobs WHERE(deleted.fldJobID = tblPrinterJobs.fldJobID)) > 0BEGINRAISERROR 44446 'The record can''t be deleted orchanged. Since related records exist in table ''tblPrinterJobs'',referential integrity rules would be violated.'ROLLBACK TRANSACTIONENDENDI can't see that this is relevant - I think it's something to do withwhere I'm updating the fldEmailProcessed field, but I need to do thishere, as outside the loop the fldJobID might be lost.Sorry it's all such a mess. Hope someone can help!ThanksEdward/*Checks all Jobs that were set to Despatched more than 24 hours ago,selects those that the companies elected to get email notification, andsends them emails.*/CREATE PROCEDURE stpSendEmailNotificationASDECLARE @rc intDECLARE @JobID intDECLARE @CompanyID intDECLARE @DocumentNumber varchar(50)DECLARE @Email varchar(50)DECLARE @DocumentURL varchar(750)DECLARE @Dat varchar(20)DECLARE @Subject varchar(100)SET @Dat = LEFT((CONVERT(varchar, GETDATE(), 100)), 11)DECLARE MailList CURSOR FORSELECTtblJobs.fldJobID,tblJobs.fldDocumentNumber,tblCompany.fldEmail,tblCompany.fldCompanyID,tblJobHistory.fldDocumentURLFROMtblJobHistory INNER JOINtblJobs ON tblJobHistory.fldJobID = tblJobs.fldJobIDINNER JOINtblDistributionMaster ON tblJobHistory.fldDistributionID =tblDistributionMaster.fldDistributionID INNER JOINtblCompany ON tblJobHistory.fldCompanyID =tblCompany.fldCompanyIDWHERE(tblJobs.fldEmailProcessed = 0)OPEN MailListFETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLWHILE @@FETCH_STATUS = 0BEGIN/* Format and send the email to the customer here */SET @Subject = N'Document Distribution No: ' + @DocumentNumber +N' - Date: ' + @Datexec @rc = master.dbo.xp_smtp_sendmail@FROM = N'techlib@myco.co.uk',@FROM_NAME = N'Edward Collier',@replyto = N'techlib@myco.co.uk',@TO = @Email,@CC = N'',@BCC = N'',@priority = N'NORMAL',@subject = @Subject,@type = N'text/plain',@message = @DocumentURL,@messagefile = N'',@attachment = N'',@attachments = N'',@codepage = 0,@server = N'12.34.5.67',@timeout = 10000select RC = @rc/* Write result to audit table */INSERT INTO tblEmailAudit(fldRCNo,fldEmail,fldDocumentNumber,fldDate,fldCompanyID)VALUES(@rc,@Email,@DocumentNumber,GETDATE(),@CompanyID)/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)FETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLENDCLOSE MailListDEALLOCATE MailListGO

View 1 Replies View Related

Create A Cursor Inside A Sproc

May 16, 2008

I try to create a Sproc which will use a cursor to retrieve a few rows from a table. But the cursor part has given me problem. Here it is:


StudentInfo
StudentID StudentName DeptID
101 John 10
102 Alex 10
103 Beth 20
ClassInfo
ClassID DeptID
901 10
902 10
225 20
I want to create a Sproc which will retreive the student's classes in DeptID 10

Following is the Sproc and cursor:

use master
go
Create PROCEDURE [dbo].[getEnclishClasses]
@StudentID int
AS
Declare @printInsertStatement nvarchar(100)
ECLARE NewRowID int

Declare classCursor CURSOR FOR
SELECT ClassID, DeptID FROM [myTest].dbo.ClassInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID)

DECLARE @ClassID INT
DECLARE @DeptID INT

OPEN classCursor
FETCH NEXT FROM classCURSOR INTO
@ClassID, @DeptID
WHILE (@@FETCH_STATUs=0)
BEGIN
PRINT 'SET @newID = Scope_Identity()'
SET @printInsertStatement=
(Select 'INSERT INTO [myTest].dbo.ClassInfo (ClassID, DeptID) Values('
+CONVERT(NVARCHAR (10), @ClassID) + ','
+CONVERT(NVARCHAR (2), @DeptID)+')'
FROM [myTest].dbo.StudentInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID))

PRINT @printInsertStatement
END
CLOSE classCursor
DEALLOCATE classCursor
EXEC getEnclishClasses 101

Here is what I try to get (text with actual data from the table):
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(901, 10)
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(902, 10)

Here is what I had got (returning multiple lines, more than number of records I have):
Msg 512, Level 16, State 1, Procedure getEnclishClasses, Line 19
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Thanks in advance for your help! Or is it a better way (not using a cursor). Each table has over 5,000 records.

View 8 Replies View Related

Copy Subtree, Recursive Sproc With Cursor Doesn't Work

Sep 20, 2007

Hi all,

I have a parent-child table, and i want to copy subtrees of it, so for instance this would be the starting point:
(id, parentId, label)
0, null, World
1, 0, US
2, 1, NY
3, 0, UK
4, 3, London

now i want to copy object 3 (UK) and it's children, so i would get
0, null, World
1, 0, US
2, 1, NY
3, 0, UK
4, 3, London
5, 0, UK_copy
6, 5, London_copy


I have this sproc:



Code Snippet

alter proc CopyObject


(@ObjectId int,

@NewParentId int)

as


declare @NewId int,

@NewName varchar


select @NewId = max(Id) + 1 from Object

select @NewName = [Name] + 'copy' from [Object] where Id = @ObjectId


-- copy object

INSERT INTO [Object]


([Id]

,[Name]

,[ParentId]

select @NewId,


@NewName,

@NewParentId

from [Object]

where Id = @ObjectId


-- copy children and set their parent to the newly created object

declare c cursor fast_forward for


select Id

from [Object]

where ParentId = @ObjectId


declare @ChildId int


open c

fetch next from c into @ChildId


while @@fetch_status = 0

begin


exec CopyObject


@ObjectID = @ChildId,

@NewParentId = @NewId

fetch next from c into @ChildId

end

close c

deallocate c





But htis throws an error that the cursor already exists:

Msg 16915, Level 16, State 1, Procedure CopyObject, Line 66

A cursor with the name 'c' already exists.

Msg 16905, Level 16, State 1, Procedure CopyObject, Line 72

The cursor is already open.

I've tried to think of an approach without cursors, but i can't figure it out. Because on the first pass, the new parentId will be the same as the parentId of the object to be copied. But the copies of the children of this first original object should have the parentid set to id of the copied object, and so all the way down the tree.

Any ideas?

Thanks in advance,

Gert-Jan

View 3 Replies View Related

You Cannot Use KILL To Kill Your Own Process. Why?

Mar 24, 1999

I'm trying to kill a bunch of processes in SQL 6.5 and I can't. I'm running the only machine with SQL tools installed on it (the server) and it won't let me kill them. I try the GUI screens and the Kill statement in ISQL_w. Is there any way around this?

I've stopped the SQL Server and rebooted the NT Server. Is there anyway I can get rid of these processes. They are locking some tables and keeping me from inserting data within my code. Very frustrating.

Thanks

View 2 Replies View Related

To Get All The SPIDs

Nov 13, 2007

is there any way to get all the SPID's running a particular Stored Proc?

Thx
Venu

View 3 Replies View Related

Hanging Spids

Feb 22, 2001

We have just combined 3 sites into one server.
Two of the sites are serving fine, however one site has spids
that won't disconnect. By the end of the day there are over 600 spids
from that one site. At first we thought it was due to the ASP pages
had a db connect, but nothing that closed that db connection. But after
they modified the pages, we are still having the same problem. Checked
the webserver and they are identical to the other webservers.
Any ideas???

View 1 Replies View Related

Let Sleeping SPIDS Lie

Jan 24, 2008

A developer came over and asked me a couple of things

1. Can C# not cleanup SPIDs and just open new ones lieing around

2. Do a large number of spids, even if they are sleeping, cause performance issues?

3. What's the Max # of spids sql server can handle?

BOL ain't too helpful right now

View 14 Replies View Related

Linguring SPIDS

Jul 23, 2005

SQL Server 2000Just curious - was wondering why some SPIDS are left hanging out therefor up to several weeks. There are no errors or anything. It looks likenormal processing.Thanks,Craig

View 1 Replies View Related

Multiple User SPIDs Which Won&#39;t Go Away??

May 22, 2001

I have an issue with a server where some users are recieving error messages along the lines of "There are currently 250 connected users etc....". the result of which is that the users sometimes can't connect. The server properties have Current Users set to 250 - I know that I could increase this figure but that doesnt't appear to be the problem.

It would seem that connections appear to stay connected even though the user has finished any server/client transactions. Also there seems to be a huge number of SPIDs even when there are only a handfull of users. Most of the 'Process Details' for these user threads show the following: "IF @@TRANCOUNT > 0 COMMIT TRAN".

What is going on and why are these Process IDs hanging around, sometimes the only option is to reboot the client PCs since trying to kill the processes just makes them reappear a few seconds later?

It could be the 32-bit client application causing it, but these problems are only on one server out of half a dozen.

Any ideas?

Thanks, Derek.

View 2 Replies View Related

SQLDataSource Cntrl - FormView Cntrl - UPD Sproc And Sproc Debugger. I Dare Anyone To Figure This One Out.

Feb 13, 2007

I have attached the results of checking an Update sproc in the Sql database, within VSS, for a misbehaving SqlDataSource control in an asp.net web application, that keeps telling me that I have too many aurguments in my sproc compared to what's defined for parameters in my SQLdatasource control.....
No rows affected.
(0 row(s) returned)
No rows affected.
(0 row(s) returned)
Running [dbo].[sp_UPD_MESample_ACT_Formdata]
( @ME_Rev_Nbr = 570858
, @A1 = No
, @A2 = No
, @A5 = NA
, @A6 = NA
, @A7 = NA
, @SectionA_Comments = none
, @B1 = No
, @B2 = Yes
, @B3 = NA
, @B4 = NA
, @B5 = Yes
, @B6 = No
, @B7 = Yes
, @SectionB_Comments = none
, @EI_1 = N/A
, @EI_2 = N/A
, @UI_1 = N/A
, @UI_2 = N/A
, @HH_1 = N/A
, @HH_2 = N/A
, @SHEL_1 = 363-030
, @SHEL_2 = N/A
, @SUA_1 = N/A, @SUA_2 = N/A
, @Cert_Period = 10/1/06 - 12/31/06
, @CR_Rev_Completed = Y ).
 
No rows affected.
(0 row(s) returned)
@RETURN_VALUE = 0
Finished running [dbo].[sp_UPD_MESample_ACT_Formdata].
The program 'SQL Debugger: T-SQL' has exited with code 0 (0x0).
And yet every time I try to update the record in the formview online... I get
Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Procedure or function sp_UPD_MESample_ACT_Formdata has too many arguments specified.Source Error:




An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
I have gone through the page code with a fine tooth comb as well as the sproc itself. I have tried everything I can think of, including creating a new page and resetting the fields, in case something got broken that I can't see.
Does anyone have any tips or tricks or info that might help me?
 
Thanks,
SMA49

View 3 Replies View Related

SQL Server 2000 Spids Blocking Themselves

Oct 19, 2005

Hey guys,

I've recently noticed some strange behaviour with sql server 2000 spid's blocking themselves. The spid will appear to be blocked for short periods of time, and then the block will disappear. I'm not sure how this could occur. It started appearing around the same time as I applied SP4.

If anyone could provide any insight into this, it would be greatly appreciated.

Cheers,
-Kilka

View 7 Replies View Related

Merge Replication And Spids Left Behind

Jul 20, 2005

We are using Merge replication with clients from remote offices (SQL2000, sp3). Recently, I have had a problem with users who arereplicating, and they shut down their laptops. The connection neverdies, and I end up with major blocking issues related to the"orphaned" spid. The tables that are blocked are used to filter dataon each client. Since the orphaned spid is blocking, backups will runforever, and have to be killed, and a SQL management job thatinserts/updates data in these tables has to be killed.If I kill the spid, it shows a rollback at 0% and the status neverchanges. The user has disconnected, and there is really nothing toroll back. How can I get rid of this spid with out restarting SQLserver, or rebooting my server?Any help would be greatly appreciated.Thanks,Amy M

View 1 Replies View Related

Can Multi-CPU Spawn Several SPIDs From One SP Execution?

Jan 24, 2008

Hi,

The myComplexProc stored proc does the following in sequence:
1. Call a UDF
2. Call another Stored Proc
3. Make a SELECT with 4 joins
4. Make another SELECT 4 joins + aggregate.

Question1: if myComplexProc is executed on 4-CPUs SQL2K Server, does it start and complete with a single SPID?

Question2: Is SQL2K smart enough to do some sort of parallelism behind the scene? If yes, can it spawn some extra SPIDs? How does it handle lock or sequencing? Because in the hypothetic scenario above Step N+1 re-uses the results of Step N so it has to wait for Step N to complete.

Thanks very much in advance for any help.

View 2 Replies View Related

SQL Server Phantom SPIDs Causes Locking And Delays

Nov 10, 2003

A fellow developer of mine has created a ASP.Net application that executes some fairly complex stored procedures. This application is for all intensive purposes a queue and 3 or 4 people work on processing items in a FIFO type environment. There is logic in the Stored procedures to make sure each worker get a unique entry using a series of query hints.

Well what we are seeing is if these works are moving at a rapid pace and we execute an sp_who2 on the sql server there are entries that that seems to be hanging there and REMAINING there even after a browser is closed or the disposed method has been called on the connection object. Has anyone else experienced something similar to this with an ASP.Net application used by mutiple people?

My inclination is to blame the design of the application, but before I do that and step on my co-workers toes I thought I would throw this out to the group.

Thanks in advance for your input.

View 7 Replies View Related

Performance Of Views Accessed By Multiple SPIDs?

Jul 23, 2005

I wonder if anyone has any hard fact based pro or contra, especially onperformance, about having views as opposed to tables when the object isbeing accessed for read only by multiple sessions/users/spids. I amparticularly concerned about the multiple instantiations of the view.Relevant thoughts on this are much appreciated.Thanks,Caveman

View 1 Replies View Related

Disconnect A User Whoz Locking The DB With Diff SPIDs

Jun 1, 2004

I have issued a simple insert statement on table and the statement could not insert a single row into the table.When i check the locks on the tables i found that almost 5000(five thousand) locks on the table for a single user with different SPID(s).
The user is and sql server user(not a windows user) and used to connect to the application.I wanted to disconnect the user from the DB so that all the locks will be freed.But i dunno how to disconnect a user from the DB. I know that i can issue KILL command to Terminate a user process based on the system process ID,but here the same user has nearly 1000 SPIDs.I thought that it would be very big job to kill each and every process and restared the sql server.but i guess its not the correct process to do.
how can i dosconnect a specific user from the DB.

Thanks.

View 1 Replies View Related

Using Do Until Or Do While Loops

Jan 24, 2002

Does anyone know if you can use do while or do until loops in stored procedures? If so what is the syntax?

thanks

Wheels

View 1 Replies View Related

For Loops?

Oct 24, 2004

Hi all.

Im trying to create a Stored Procedure that inserts multiple rows. But I can't get it to work.

Here's how I would like it to work

for test in (select myid from tblPlayers)
begin
Insert into tblMatches VALUES(test.myid, 2)
end

but obviously it does not work. Any ideas?

View 1 Replies View Related

Loops In SQL

May 6, 2008

Can i have equvivalent loop in SQL for the following C lannguage Loop.
I am not able to generate Loop of this kind in MSSQL Store procedures.

i=10;
Do { Statement 1 ;
Statement 2 ;
i-- ';
} while i=0 ;

View 2 Replies View Related

Help With While Loops

Aug 23, 2007

hi,
I am trying to
1)get all the names of a table that match another table
2)if count=0, then I want to insert into another table 'group' after getting its key.

I am totally lost, can somebody point me in the right direction.

how do I get the individual name so that I can insert into the group table,
I tried 'select @name=name, that gave no results'.
Thanks

while (SELECT name FROM names WHERE name in (select name from Group) and status = 'M' )=0
begin
insert into group(group_id,name,action) values (@key, name, 'play' )
end

View 5 Replies View Related

Help With While Loops

Aug 23, 2007

hi,I am trying to1)get all the names of a table that match another table2)while count=0, then I want to insert into another table 'group'after getting its key.I am totally lost, can somebody point me in the right direction.how do I get the individual name so that I can insert into the grouptable,I tried 'select @name=name, that gave no results'.Thankswhile (SELECT name FROM names WHERE name in (select name from Group)and status = 'M' )=0begininsert into CAll(group_id,name,action) values (@key, name, 'play' )endhow do i get the individual names to insert into another table ..

View 2 Replies View Related

Too Many Loops For Query?

Aug 17, 2006

Hi, I have below psuedo code ... it will display correct result, however, it takes a bit longer time to display all results. I think it's because we have so many loops, and each record from the loop will do a query from database. I need some advice about how to speed up the process time. Thanks in advance.
...
Do While NOT RS.EOF
        SQL_1 = "SELECT * FROM TB1" ;
        Set RS2 = Conn.Execute(SQL_1);
         Do WHILE NOT RS2.EOF
                 SQL_2 = "SELECT * FROM TB2 WHERE NAME=" + RS2.FIELDS("Name");
                 Set RS3 = Conn.Execute(SQL_2);                    
                 DO WHILE NOT RS3.EOF
                          SQL_3 = "SELECT * FROM TB3 WHERE AGE=" + RS3.FIELDS("Age");
                          Set RS4 = Conn.Execute(SQL_3);                    
                          DO WHILE NOT RS4.EOF
                                     Response.Write RS4.FIELDS("VAL");
                         loop
                   loop
        loop 
loop
...

View 1 Replies View Related

Help With Nested Loops

Jun 27, 2007

Hi. newbie here.
Also new to coding in SQL.

Struggling with how to implement the following psuedo-code in SQL server 2000.
** Can you use more than one CURSOR variable?
If yes, when use FETCH_STATUS is it for cur1 or cur2 ??

Sample data is at the bottom.
Thanks for ANY suggestions !!

** Assume TABLE 1 is sorted by Record_Type, Order_no, Order_line_no

************************************************** ***
dim @rectyp
dim @ord#
dim @lin#

Fetch (?) 1st record in TABLE1
While Still Records in TABLE1
Set sub_line# = 0
set @rectyp = Record_Type,
set @ord# = Order_no,
set @lin# = Order_line_no

while @rectyp = Record_Type and
@ord# = Order_no and
@lin# = Order_line_no
Set sub_line# = sub_line# + 1
update TABLE1 set line_ctr = sub_line#
get next record
end inner WHILE

end outer WHILE

************************************************** ****************************
Sample data :
Data as it currently exists:
Record_type ......Order No......Order line no ......Line Ctr
OP.....................458001................5.... ...............0
OP .....................458001..............5 .................. 0
OP..................... 458001..............5..................0
OP .....................458001..............5........ ..........0
OP.....................458191..............1 ..................0
OP.....................458191..............1 .................. 0
OP..................... 458308..............73..................0
OP .....................458308..............73....... ........... 0
OP.....................458308..............73..... .............0
OP.....................458308..............73..... .............0


Want data to look like this after executing code:
Record_type ......Order No......Order line no ......Line Ctr
OP.....................458001................5.... ...............1
OP .....................458001..............5 .................. 2
OP..................... 458001..............5..................3
OP .....................458001..............5........ ..........4
OP.....................458191..............1 ..................1
OP.....................458191..............1 .................. 2
OP..................... 458308..............73..................1
OP .....................458308..............73....... ........... 2
OP.....................458308..............73..... .............3
OP.....................458308..............73..... .............4


************************************************** *********************

View 2 Replies View Related

Loops And Cursors

Oct 26, 2007

I have a stored procedure that I am trying to write. I want it to Grab a list of ids from one table, then loop through that list and select a group of records from a second table based on the first list. The 2nd list can have 1 + records per item from the first list. With in that record, I need to check the values in 2 fields, if the values = something I update a third field and move on to the next. So I need to be able to loop thru the second set also. Currently I have a cursor with in a cursor, but was told that was slow and not a good idea, so I am trying to figure out what other options I have.

Thanks in Advance

Swoozie

View 9 Replies View Related

For Loops In Tsql

Jan 29, 2007

Can somebody please tell me how can i write a tsql statement in sql server 2000.

Same time how can i get the last digit of a inteager variable through tsql .What i want is to write 'right(intVariable,4) which is in vb .I want that in sql server 2000



Thank you

View 8 Replies View Related

Loops And Transaction Log

Apr 2, 2008



I brought my server to it's knees by creating 499.9GB of transaction log on a 500GB drive. Oops.

The db recovery model is SIMPLE.

I want to loop through some code, and minimize the transaction log file size. My second query here has an explicit transaction. Assume this code will loop about....1/2 Billion times. Is one (or both) of these going to record ALL 500,000,000 update statements in the Transaction Log (remember SIMPLE recovery)? Will the second one of these record a single transaction 500,000,000 time but not overwhelm the Log file due to simple recovery?

Any thoughts anyone?




Code Snippet
declare @i bigint
select @i = min(ID) from <MyTable>
While @i is not null

begin

update <MyTable> set <SomeField> = <SomeValue> where ID = @i
select @i = min(id) from <MyTable> where ID > @i
end






Code Snippet
declare @i bigint
select @i = min(ID) from <MyTable>
While @i is not null

begin

BEGIN TRANACTION


update <MyTable> set <SomeField> = <SomeValue> where ID = @i
COMMIT
select @i = min(id) from <MyTable> where ID > @i
end

View 1 Replies View Related

SQL Server Admin 2014 :: MDW Data Collector - Large Number Of SPIDs

Nov 6, 2015

I've installed the MDW (Mangement Data Warehouse) database on our central monitoring SQL Server. I've then added a number of servers to be monitored. The data is collected on the servers that are being monitored and uploaded to the central MDW Monitoring server.

On the servers that are being monitored, I'm seeing a large number (over 1000) of SPIDs being generated by 'SQL Server Data Collector'.

Is this normal behaviour? I've seen more blocking as a result of this.

Is there any way to reduce the number of SPIDs generated?

View 0 Replies View Related

Loops In Stored Procedures

Jan 20, 2008

How can I create a query and loop through all its records in a stored procedure?

View 2 Replies View Related

Stored Procedures And For Loops

Jun 2, 2004

Hi, I'm trying to call a stored procedure in a for loop within an ASPX page. My code runs fine but it seems to skip over the function which uses the stored procedure. The procedure basically copies files from the the client to the server. I have the upload portion working which physically copies the files from the client to server but when it comes to copying the path into a field in a table it totally skips it.

Some one suggested that the for loop is operating too fast for the stored procedure to work.

Any suggestions

View 1 Replies View Related

Help With Where Not Exists / Avoiding Loops

Mar 18, 2008

I am trying to figure out an efficient way of comparing two tables of identical structure and primary keys only I want to do a join where one of the tables reveals values for records which have been modified and/or updated.

To illustrate, I have two tables in the generic form:

id-dt-val

For which the 'val' in table 2 could be different from the 'val' in table 1 - for a given id-dt coupling that are identical in both tables.

Does anyone know of an efficient way I could return all id-dt couplings in table 2 which have values that are different from those with the same id-dt couplings in table 1?

NOTE: I am asking this because I am trying to avoid explicit comparisons between the 'val' columns. The tables I am working with in actuality have roughly 900 or so columns, so I don't want this kind of a monster query to do (otherwise, I would simply do something like where a.id = b.id and a.dt = b.dt and a.val <> b.val) - but this won't do in this case.

As a sample query, I have the following script below. When I attempt the where not exists, as you might expect, I only get the one record in which the id-dt coupling is different from those in table 1, but I'm not sure how to return the other records where the id-dt coupling is the same in table 1 but for where modified values exist:


create table #tab1
(
id varchar(3),
dt datetime,
val float
)
go

create table #tab2
(
id varchar(3),
dt datetime,
val float
)
go


insert into #tab1
values
('ABC','01/31/1990',5.436)
go
insert into #tab1
values
('DEF','01/31/1990',4.427)
go
insert into #tab1
values
('GHI','01/31/1990',7.724)
go


insert into #tab2
values
('XYZ','01/31/1990',3.333)
go
insert into #tab2
values
('DEF','01/31/1990',11.111)
go
insert into #tab2
values
('GHI','01/31/1990',12.112)
go


select a.* from #tab2 a --Trouble is, this only returns the XYZ record
where not exists
(select b.* from #tab1 b where a.id = b.id and a.dt = b.dt)
go

drop table #tab1
drop table #tab2
go

I really dont' want to have to code up a loop to do the value by value comparison for inequality, so if anyone knows of an efficient set-based way of doing this, I would really appreciate it.

Any advice appreciated!

-KS

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved