Transact SQL :: Does Fetch Status In Nested Loops Conflict
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.
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
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?
I write few lines to do a bottom-up calculation, with 'fetch last' and 'fetch prior'.
It seems that the condition 'WHILE @@FETCH_STATUS = 0' does not work when cursor arrives at the first line, as there is an error message:
'(1 row(s) affected) 6255.84 (1 row(s) affected) Msg 16931, Level 16, State 1, Line 18
There are no rows in the current fetch buffer.
The statement has been terminated.'
how to fix the error?
Here is my code:
DECLARE @lastprice real DECLARE @updatedprice real DECLARE @updatedRe real DECLARE @updatedAUX real SET @lastprice = ( SELECT Close_P from #ClosePrice where #ClosePrice.DateTD = (SELECT MAX(#ClosePrice.DateTD) FROM #ClosePrice) )
However, with the Customers changing their addresses and having multiple records of different dates in Table_B how to reflect the Latest address of the same in the requisite View?In other words Cust_Id (AB), Cust_Name (CD), who as per Table_B have 100 records with three different addresses (EF, GH & IJ) spread over two years. How to fetch the only latest address in this case? i.e. a record in View_C as:
I am using the following code to get the next immediate parent of a customer in the hierarchy and it works fine. However, it works only for one customer at a time (i made this a scalar function and I pass the customer id as shown below).
How can I modify this so that i can get each customer and its next immediate parent (all of them in one shot in a single data set)?
WITH my_cte (CustomerID, ParentID, Level) AS ( SELECT CustomerID, ParentID, 0 AS Level FROM [dbo].MyTable WHERE CustomerID = @CustomerID
UNION ALL SELECT CustomerID, ParentID, Level + 1 FROM [dbo].MyTable e INNER JOIN my_cte AS cte ON e.CustomerID = cte.ParentID )
select CustomerID from my_cte WHERE Level <> 0 AND Level = (SELECT MIN(Level) FROM my_cte WHERE Level <> 0)
I need the rows updated today in catalogue table irrelevant of timing. I tried all the below queries.
select * from CATALOGUE where CAT_DATE=CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)) select * from CATALOGUE where CAT_DATE= CONVERT(date, getdate()) select * from CATALOGUE where CAT_DATE= cast(GETDATE() as date)
I am getting output only if the information updated on 04/21/2015 00.00.00.000 but not for other timings, For example 04/21/2015 03.30.00.000, 04/21/2015 07.17.00.000 and all.
I currently have a transactional replication between SQL Server 2000 and an Oracle database. Once a week on Monday mornings we have a process that drops replication, uploads data to the SQL Server database from Oracle, does some manipulation of the data and then recreates replication.
We came across the thought of what would happen if replication had erred out and there were still transactions within the distribution database to be replicated across. Then our job just came about and dropped the replication.
We are looking for a way to tell what the status is of replication through Transact-SQL. This way we can check the status and if it contained an error that we could abort the job, so as to not lose any transactions.
Does anyone have an idea of how to accomplish this?
In my database I have an Audit table, that keeps track of teams worked upon the same record in a workflow.I need to find out how many records have been returned to the first team for correction ?The column 'Status' is numbered from 1 to 6 and Column 'EditTime' saves the time when record has been edited.how many records have been returned for correction and identify those records.
I have a table like above where cid is unique but status is not for all the status id i need put 1 as they sent out .but till now i used max listindex because they used to send files sequentially but now list index is random so how to update sent to 1 for all the status ids.
I have a query which works absolutely fine when connecting to an actual server:
WITH CLAIMDATA AS( SELECT DISTINCT DB_NAME() AS DBName, 'UA' AS Client, POLICY AS KMPONO,
[code]...
If i change the connector to REPLPROD (which is a linked server): From REPLPROD.XUNMDTAUAI.dbo.UPPOREP UP INNER JOIN REPLPROD.XUNMDTAUAI.dbo.UKKMREP UK
I get the error:
Msg 8180, Level 16, State 1, Line 1 Statement(s) could not be prepared. Msg 125, Level 15, State 4, Line 1
Is there any way to convert a bind variable, which is a list of integer or string values, to nested table in MS SQL Server. I am looking for something like
CAST in Oracle, which converts a varray type column into a nested table. Do we have something like this in SQL Server.
in Oracle:
SELECT CAST(s.addresses AS address_book_t) FROM states s WHERE s.state_id = 111;
I have read about Table valued Parameter, but I am looking for another solution.
I have been wrestling with the code all day to accomplish the following: I need to update a table based on values from another table. So far, I have been able to do the below:
DECLARE @LookUpTerm VARCHAR(25) , @SearchCol VARCHAR(255) , @LogonIDToProcess VARCHAR(50) , @Matched CHAR , @Cycle INT = 1 IF OBJECT_ID('tempdb..#Glossary','U') IS NOT NULL DROP TABLE #Glossary IF OBJECT_ID('tempdb..#Employees','U') IS NOT NULL DROP TABLE #Employees
I need to perform an update where there are multiple scenarios which determine the value that is entered. Below is a sort've psuedo code of how it needs to be.
Update MyTable SET MyColumn = CASE WHEN MyCol1 = 'Value1' Then NewValue Else WHEN MyCol1 <> 'Value1' And MyCol2 = 'Active' Then 'Value1'
In the scenario where MyCol1 <> Value1 and MyCol2 <> 'Active' then no update would occur and the original value would remain intact.
I have a scenario to fetch records for each ID on 2 conditions. There are 2 types of Product type for each ID. PFE and PRI. I need only latest active PFE and at the same time all the latest PRI should be closed. (meaning, only PFE should be in Active status currently)
1.) Latest Product type PFE should be A (active) status for the particular ID 2.) At the same time ALL the latest PRI should be C(closed) status for the same ID
I have give example with 3 scenarios and desired output
1.) For ID 101, Latest PFE is active and all latest PRI is closed ----> Should come in result 2.) For ID 102, Latest PFE is Closed and all latest PRI is closed ---->Should NOT come in result
We have a required to run multiple procedures in Single Go . And Error Occurred in any Procedure the it will rollback all the changes( Either all Proc run or None)
Problem Statement is its not capturing the Error Message from Either Proc1 or Proc 2., its Capturing the Flat Message (The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction). How do i capture the Error Occurred in Proc 1 or Proc 2 into Log Tables.
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
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 ..
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 ...
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.
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)
--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;
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
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
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.
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.
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)
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
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.