How To Avoid Cursors And Loops
Sep 26, 2006
hi,
My problem is basically i need to call a stored proc for each entry in a table, i.e, basically a for loop calling stored procs with parameter coming from the table. I know two ways of doing this .. using cursor and using while loop with temp table. I dont like both approaches. Is there any good practice for this situation..
declare mycur cursor fast_forward for select ID from sometable
open mycur
FETCH NEXT FROM mycur
INTO @AID
WHILE @@FETCH_STATUS = 0
begin
exec dbo.storedproc @AID
FETCH NEXT FROM mycur INTO @AID
end
CLOSE mycur
DEALLOCATE mycur
View 13 Replies
ADVERTISEMENT
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
Jul 23, 2005
Hi All,I want to avoid using cursors and loops in stored procedures.Please suggest alternate solutions with example (if possible).Any suggestion in these regards will be appreciated.Thanks in advance,T.S.Negi
View 22 Replies
View Related
Jul 23, 2005
i'm trying to write a batch that will perform a complex task usingset-based selects instead of a row-based cursor. let me know if you canhelp me figure out how.description of what i'm trying to do:there is TABLE1, TABLE2, and TABLE3i want to select each row from TABLE1, do some analysis on the data ofthat row, and then perform an insert of some data into TABLE2, and somedata into TABLE3how do i do this in a T-SQL batch?
View 9 Replies
View Related
Feb 28, 2006
I have a long sql batch that does this:1. Gets a list of all tables in user database that start with name COREdeclare@tablenamevarchar(30),@commandvarchar(2000),@cntintegerdeclare GetCOREOids cursor forselect sysobjects.namefrom sysobjectswhere ( OBJECTPROPERTY(sysobjects.id,N'IsUserTable')=1 ) and( sysobjects.name like 'CORE%' or sysobjects.name ='CMNSTRStructGeomBasicPort') and( sysobjects.name not like 'CORESpatialIndex%') and (sysobjects.namenot like 'COREDeletedObjects%') and( sysobjects.name not in('CORERelationOrigin','CORERelationDestination') ) and( sysobjects.id in ( select id from syscolumns where name = 'oid') )for read only2. Populates a temporary table with distinct oids from the list.create table [#tSP3DCoreOid] (oid UNIQUEIDENTIFIER)open GetCOREOidsfetch GetCOREOids into @tablenamewhile ( @@fetch_status = 0)beginselect @command = 'insert into [#tSP3DCoreOid] select distinct oid from' + @tablenameexecute(@command)--print @tablename + ' rows: ' + convert(char,@@rowcount)fetch GetCOREOids into @tablenameend /* while */--Clean upclose GetCOREOidsdeallocate GetCOREOids3. Creates a cursor to get "invalid" oids from 2 other tablesdeclare DanglingRelation cursor forselect oid from [dbo].[CORERelationOrigin] RO where not exists( select oid from [#tSP3DCoreOid] where oid = RO.oid )unionselect oid from [dbo].[CORERelationDestination] RD where not exists( select oid from [#tSP3DCoreOid] where oid = RD.oid )4. Loops thru. the cursor examining each oid and then calls aStoredProc to update another tabledeclare @objectOid uniqueidentifierdeclare @tempOid uniqueidentifieropen DanglingRelationfetch DanglingRelation into @ObjectOidwhile ( @@fetch_status = 0)beginset @tempOid='00000000-0000-0000-0000-000000000000'if left(@ObjectOid,8)='00000002'select @tempOid=oid from COREToDoList where Oid=@ObjectOidelse if left(@ObjectOid,8)='00000003'select @tempOid=oid from COREToDoRecord where Oid=@ObjectOidelse if left(@ObjectOid,8)='00000004'elseselect @tempOid=oid from COREBaseClass where Oid=@ObjectOidif @tempOid = '00000000-0000-0000-0000-000000000000'BEGINexec CORESetObjectIntegrity @ObjectOid, 2ENDfetch DanglingRelation into @ObjectOidendclose DanglingRelationdeallocate DanglingRelationdrop table [#tSP3DCoreOid]Now the #tSP3DCoreOid temp table can sometimes get as many as 7.5million rows and this is making the batch fail on SQLServer as it runsout of memory.I think the problem is the cursor here and would like somefeedback/tips on how to best optimise it.thanks a lotSunit
View 4 Replies
View Related
Oct 30, 2006
Hi,
I have a customer who is using vba to pull a result set from an sql server stored procedure into excel. She wants a calculated column added to the result set that gives:
The number days (datediff) between the end date (autend_dte) on one row and the begin date (autbeg_dte) on the next row for each client (clt_num). The rows are to be ordered by client and begin date. The number should be associated with the second row used to calculate the date diff. The first row for each client will have a date diff of 0.
I could do this using a cursor in the stored procedure or a loop in the vba, but I would prefer to do it with the select, but I don't even know where to start.
See expected results below.
CREATE TABLE #testit (
clt_num int NOT NULL ,
autbeg_dte datetime NULL ,
autend_dte datetime NULL)
INSERT INTO #testit (clt_num, autbeg_dte, autend_dte)
SELECT 510, '2004-09-01 00:00:00.000', '2005-09-30 23:59:00.000' UNION ALL
SELECT 510, '2005-10-01 00:00:00.000', '2006-04-06 23:59:00.000' UNION ALL
SELECT 600, '2006-08-01 00:00:00.000', '2006-11-06 23:59:00.000' UNION ALL
SELECT 2529, '2006-01-13 00:00:00.000', '2006-04-11 23:59:00.000' UNION ALL
SELECT 2529, '2005-11-30 00:00:00.000', '2005-12-12 23:59:00.000' UNION ALL
SELECT 2602, '2006-03-29 00:00:00.000', '2006-05-02 23:59:00.000' UNION ALL
SELECT 2602, '2005-11-12 00:00:00.000', '2006-02-27 23:59:00.000' UNION ALL
SELECT 2602, '2006-05-26 00:00:00.000', '2006-06-12 23:59:00.000' UNION ALL
SELECT 2602, '2006-06-18 00:00:00.000', '2006-06-28 23:59:00.000'
SELECT * FROM #testit
order by clt_num,autbeg_dte
Expected result:
clt_numautbeg_dte autend_dte Days Diff
5102004-09-01 00:00:00.0002005-09-30 23:59:00.0000
5102005-10-01 00:00:00.0002006-04-06 23:59:00.0001
6002006-08-01 00:00:00.000 2006-11-06 23:59:00.000 0
25292005-11-30 00:00:00.0002005-12-12 23:59:00.0000
25292006-01-13 00:00:00.0002006-04-11 23:59:00.00044
26022005-11-12 00:00:00.0002006-02-27 23:59:00.0000
26022006-03-29 00:00:00.0002006-05-02 23:59:00.00030
26022006-05-26 00:00:00.0002006-06-12 23:59:00.00024
26022006-06-18 00:00:00.0002006-06-28 23:59:00.0006
Thanks,
Laurie
View 15 Replies
View Related
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
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
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
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
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
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
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
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
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
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
Jan 20, 2008
How can I create a query and loop through all its records in a stored procedure?
View 2 Replies
View Related
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
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
Nov 16, 2007
I need help creating the following report.
I need to modify the folliwng report to produce a weekly version of it.
To get a weekly version, simply find the first day of the week for the @dtm1 value :
should be something like @firstofweek=dateadd(day,(datepart(dw,@dtm1)*-1)+1,@dtm1) to get the Sunday date
I think i will then then need to loop through from firstofweek to last of week (last of week will be the Saturday)
would suggest having a dayofweek column on your temporary table.
CREATE PROCEDURE rpt_siteMealListWeekly
@dtm1 AS DATETIME
,@cmb1 AS VARCHAR(100)
WITH ENCRYPTION
AS
--DECLARE @dtm1 AS DATETIME
DECLARE @siteid as integer
SELECT @siteid=siteid from site where sitename=@cmb1
--SELECT @dtm1='2007-09-13',@siteid=1
--select convert (char(11),@dtm1,113)
DECLARE @mybit AS INTEGER
SET @mybit=10
SELECT @mybit = CASE datepart(dw,@dtm1)
WHEN 1 THEN 1 -- 'Sunday'
WHEN 2 THEN 2 -- 'Monday'
WHEN 3 THEN 4 -- 'Tuesday'
WHEN 4 THEN 8 -- 'Wednesday'
WHEN 5 THEN 16 -- 'Thursday'
WHEN 6 THEN 32 -- 'Friday'
WHEN 7 THEN 64 -- 'Saturday'
END
CREATE TABLE #tmp_table(
childid INTEGER null
,br BIT null
,di BIT null
,te BIT null
,type integer default 0
)
INSERT #tmp_table
SELECT DISTINCT sa.childid
,CASE WHEN sha.br & @mybit>0 THEN 1 ELSE 0 END
,CASE WHEN sha.di & @mybit>0 THEN 1 ELSE 0 END
,CASE WHEN sha.te & @mybit>0 THEN 1 ELSE 0 END
,0
FROM
sessionAttendance sa
,simplehoursassignment sha
,session s
,child c
WHERE
sha.childid=sa.childid
AND
sha.siteid=sa.siteid
AND
s.siteid=sa.siteid
AND
c.siteid = sa.siteid
AND
c.childid = sa.childid
AND
sa.siteid=@siteid
AND
s.identityid=sa.identityid
AND
s.dayofweek=datepart(dw,@dtm1)
AND
s.siteid=sa.siteid
AND
@dtm1 between cast(floor(cast(sa.datefrom as float))as smalldatetime) and cast(floor(cast(sa.dateto as float))as smalldatetime)
AND
sa.userdefid=0
AND
(
--check not a company holiday
not exists
(select
1
from
companyholidays ch
where
siteID=@siteID
and
@dtm1 between cast(floor(cast(ch.datefrom as float))as smalldatetime)
and
cast(floor(cast(ch.dateto as float))as smalldatetime)
)
)
and
(
sa.childid in
View 3 Replies
View Related
Jan 11, 2006
I have a problem when using nested loops in my Control Flow. The package contains an outer Foreach Loop using the Foreach File Enumerator which in my test case will loop over two files found in a directory. Inside this loop is another Foreach Loop using the Foreach Nodelist Enumerator. Before entering the inner loop a variable, xpath, is set to a value that depends on the current file, i e /file[name = '@CurrentFileName']/content. The Nodelist Enumerator is set to use this variable as its OuterXPATHString. Now, this is what happens:
First Iteration:
The first file is found and the value of xpath = /file[name = 'test1.txt']/content. When the inner loop is entered it iterates over the content elements under the file with name test1.txt as expected.
Second Iteration:
The second file is found and the value of xpath = /file[name = 'test2.txt']/content. When the inner loop is entered it unexpectedly still iterates over the content elements under the file with name test1.txt.
My question is: Should it not be possible to change the loop condition of an inner loop in an outer loop such that the next time it is entered it will be done based on the new condition? It seems that the xpath variable is read once, the first time, and never again. If that is the case, does anyone know of a workaround?
Regards,
Lars Rönnbäck
View 8 Replies
View Related
Jun 29, 2006
It would appear that if a Child package is called more than once from a Parent using the 'Execute Package' task, then after the first execute the Parent Package Variables are not applied to child package. I.E we build dimensions in a master database and these are then loaded to a number of topic specific datamarts. We simply pass Parent variables to the child that hold source & target connection strings, the first time the package is called the correct database is accessed, subsequent Executes ignore the variables and use the original values. Manipulating the (our) event queue to run the package once results in the correct behaviour
Are packages cached when they are called from a Parent? if so is there a flag that I have missed to force a reload each time a child is executed?
This has just become a big problen for us so any guidance would greatly appreciated.
Paul
View 6 Replies
View Related
Oct 9, 2006
The problem:
I have 2 tables, with a one to many relationship - lets say customers, and order items.
Each order record has a field that is meant to be a comma delimited list (they are reference numbers) that is driven by the quantity field. So, say in the order record, an item has a quantity of 3. The reference number will look like this:
1, 2, 3
And if the next order item for that customer has a quantity of 4, the reference number value is
4, 5, 6, 7
And the final item with quantity of 2:
8, 9
Reference numbers can either be auto assigned (and are in my web application) or manually set. If manually set they will NOT be numeric.
In my web application, it is possible for users to return to a customer's order and edit a line item. My problem is when users changes the quantity of an item, and I have to reset the reference numbers.
If the quantity of line item 2 changes from 4 to 3, I need to reset all the values for that, and any other, order item that comes after it:
4, 5, 6 (2nd)
7,8 (3rd with same quantity of 2).
I felt a cursor would be the best way to handle this. But I am having trouble re-assigning my variable to be the next number in the series when the cursor is running.
This is what I have so far. The print lines and hard coded values are for debugging purposes only.
DECLARE @NumberingType varchar(10)
DECLARE @TotalSum int
DECLARE @DoorLineItemID int
DECLARE @Quantity int
DECLARE @SeedInt int
SET @SeedInt = 1
SELECT @TotalSum = SUM(Quantity) FROM DoorLineItems WHERE UniversalOrderID = 12345
DECLARE UpdateRefCursor CURSOR FOR
SELECT DoorLineItemID, Quantity FROM DoorLineItems WHERE UniversalOrderID = 12345 AND NumberingType = 1
OPEN UpdateRefCursor
FETCH NEXT FROM UpdateRefCursor INTO @DoorLineItemID, @Quantity
DECLARE @RefNumberLine varchar(1024)
SET @RefNumberLine = ''
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE @SeedInt <= @Quantity
BEGIN
SET @RefNumberLine = @RefNumberLine + CONVERT(varchar, @SeedInt, 101) + ', '
SET @SeedInt = @SeedInt + 1
END
PRINT @RefNumberLine
SET @SeedInt = @Quantity + @SeedInt
PRINT 'new seed: ' + CONVERT(varchar, @SeedInt, 101) + 'Quantity ' + CONVERT(varchar, @Quantity + @SeedInt, 101)
FETCH NEXT FROM UpdateRefCursor INTO @DoorLineItemID, @Quantity
END
CLOSE UpdateRefCursor
DEALLOCATE UpdateRefCursor
This returns the same delimited string for X number of items. So I'm getting this:
1,2,3
1,2,3
1,2,3
When I really want the results described above.
What am I doing wrong?
Thanks!
View 2 Replies
View Related
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
View Related
Sep 28, 2005
The trick is to use a pivot tableCheck out the code herehttp://sqlservercode.blogspot.com/2...ops-in-sql.html
View 3 Replies
View Related
Apr 24, 2015
Does fetch status in nested loops conflict?I have a script that should output a cluster record line and for each cluster record it must create a line for each household in the cluster. All the data is pulled from one table, 'LFS_APRIL_2015.dbo.LISTING'.This is the script:
--VARIABLE DECLARATION
DECLARE @CLUSTER FLOAT, @HOUSEHOLD_NUMBER FLOAT, @FULL_ADDRESS CHAR(50), @HEAD_NAME CHAR(24)--CLUSTER LOOP
DECLARE CLUSTER_CURSOR CURSOR FOR
SELECT [LFS_APRIL_2015].[dbo].[LISTING].CLUSTER
from [LFS_APRIL_2015].[dbo].[LISTING] where CLUSTER IS NOT NULL and DISTRICT = 1
OPEN CLUSTER_CURSOR
[code]...
It appears however that the clusters are being repeated.
View 5 Replies
View Related
Jul 16, 2006
Hello,
Can anyone direct me a good article that is about why we should try avoiding using cursors and what are the alternatives?
View 1 Replies
View Related
Feb 16, 2008
can we call cursors from asp.net as we can call stored procedures from asp.net.
View 1 Replies
View Related
Jan 7, 2005
Hi,
I'm writting a stored procedure to insert new rows into a table, but I need to loop through an exsiting table and create a new record for every row in the old table. So I think what I'm needing to use is a cursor, but I've never worked with cursors before, and I just want to check that I have the right idea on what they are used for and if what I have so far looks ok.
This what I have so far, the StoreFees table only has 5 rows:
DECLARE @StoreFee as smallmoney
DECLARE @StoreLineID as int
DECLARE MyStoreFees CURSOR
FORWARD_ONLY
FOR
SELECT LineId, StoreFee FROM StoreFees ORDER BY StoreFee
OPEN MyStoreFees
FETCH NEXT FROM MyStoreFees
INTO @StoreLineId, @StoreFee
--Do my Inserts into other tables
INSERT INTO OtherTable (...,...,.., @StoreFee)
...
...
-- Done working with that row
CLOSE MyStoreFees
View 5 Replies
View Related
Feb 28, 2005
I am trying to pull the data via fetching rows into a variable.
Begin
Fetch Next Into @temp...
Select @MainVariable = @MainVariable + @temp < @temp doesn't refresh with next fetch)
Print @temp < this works fine and returns the value for each fetch
End
I can print @temp and the data returns fine, but when I try to cancantenate with the above select, it doesn't refresh @temp wit the column in the table.
Any ideas?
DotNetNow
View 5 Replies
View Related
Jun 19, 2001
I have two procedures. One works well, and the other has a small glitch I cannot figure out. I have placed >>>> at the place where the problem is occuring.
The first procedure, which is working great, is applying a stored procedure to many servers (remote procedure call), but is also polling the local server via a linked server connection. This way, all servers are polled equally.
The second procedure is actually using a SELECT statment to query a system table. This procedure works well on all servers except the local one. I get this error message:
Server: Msg 3910, Level 16, State 1, Line 1
Transaction context in use by another session.
[OLE/DB provider returned message: Unspecified error]
There seems to be a connection issue. Can someone help me work around this?
Thank you,
Neal
FIRST PROCEDURE (this one works perfectly):
truncate table dbidname
CREATE TABLE ##dbtemp ( dbname VarChar(50),
dbsize varchar (25),
dbownervarchar(50),
dbid smallint,
createdate datetime,
statusvarchar(75) )
declare@servernamevarchar(50)
declare dbupdate cursor
global
for
select servername from sqlservers where status = 'a'
open dbupdate
fetch next from dbupdate into @servername
while @@fetch_status = 0
begin
print @servername
EXEC sp_addlinkedserver @servername, 'SQL Server'
>>>INSERT INTO ##dbtemp
>>>exec (@servername + '.master..sp_helpdb')
alter table dbidname alter column sqlservers_id int null
insert into dbidname (dbsystemid, dbname)
select dbid, dbname from ##dbtemp
update dbidname set sqlservers_id = sqlservers.sqlservers_id from sqlservers where @servername = sqlservers.servername and
dbidname.sqlservers_id is null
update dbidname set whenupdate = getdate()
alter table dbidname alter column sqlservers_id int not null
exec sp_dropserver @servername
delete ##dbtemp
fetch next from dbupdate into @servername
end
close dbupdate
deallocate dbupdate
drop table ##dbtemp
exec spal_db_files_update
SECOND PROCEDURE (see >>>> to note problem area):
truncate table dbidname
CREATE TABLE ##dbtemp ( dbname VarChar(50),
dbsize varchar (25),
dbownervarchar(50),
dbid smallint,
createdate datetime,
statusvarchar(75) )
declare@servernamevarchar(50)
declare dbupdate cursor
global
for
select servername from sqlservers where status = 'a'
open dbupdate
fetch next from dbupdate into @servername
while @@fetch_status = 0
begin
print @servername
EXEC sp_addlinkedserver @servername, 'SQL Server'
>>>>INSERT INTO ##dbtemp
>>>>exec (@servername + '.master..sp_helpdb')
alter table dbidname alter column sqlservers_id int null
insert into dbidname (dbsystemid, dbname)
select dbid, dbname from ##dbtemp
update dbidname set sqlservers_id = sqlservers.sqlservers_id from sqlservers where @servername = sqlservers.servername and
dbidname.sqlservers_id is null
update dbidname set whenupdate = getdate()
alter table dbidname alter column sqlservers_id int not null
exec sp_dropserver @servername
delete ##dbtemp
fetch next from dbupdate into @servername
end
close dbupdate
deallocate dbupdate
drop table ##dbtemp
View 1 Replies
View Related
Nov 28, 2000
I am receiving this error when running my cursor:
Error Messages...
Server: Msg 16933, Level 16, State 1, Line 0
The cursor does not include the table being modified.
The statement has been terminated.
Server: Msg 16933, Level 16, State 1, Line 5 (this message repeats)...
The cursor does not include the table being modified.
The statement has been terminated.
query:
declare cursor_test CURSOR for
select emp_ssn, effective_date1 from temp_employee_benefit_load
open cursor_test
declare @ssn char(9), @process_date char(8)
fetch next from cursor_test into @ssn, @process_date
while (@@fetch_status=0)
update test_cursor
set ssn = @ssn, process_date = @process_date
where current of cursor_test
fetch next from cursor_test into @ssn, @process_date
close cursor_test
deallocate cursor_test
Any help is appreciated:
Thanks,
View 3 Replies
View Related
Sep 7, 2000
I have stored procedure in that I am using a cursor to fetch the row by row.
cursor is fetching 75000 records so that the procedure is taking long time.
Is there any way to replace the cursor to fetch the records row by row.
He needed.
Ranch
View 1 Replies
View Related