I Am Trying To Use Nested Cursors. But Is There A Way To Use More Than One @@FETCHSTATUS Variable ?
Apr 18, 2008
I need to use a nested cursor in SQL server 2005. I have never done this before. The problem here is that I need to use "@@FETCH_STATUS' twice.
Once for my inner loop and once for my outer loop. If there is a way to use two different @@FETCH_STATUS variables at once, I would like to know how.
Here is my code. The inner loop is currently pseudo code and I just need to figure out how to code it.
DECLARE @mycur1 CURSOR
DECLARE @mycur2 CURSOR
DECLARE @InMarketId INT
SET @InMarketId=575 -- Hard code for now. Just for testing.
DECLARE @test VARCHAR(10)
SET @mycur1 = CURSOR
SET
FOR
SELECT SubDivisionId FROM SubDivision WHERE MarketId=@InMarketId
OPEN @mycur1
FETCH NEXT FROM @mycur1 INTO @test
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @test
-- Begin Inner Nested Loop
-- FOR EACH SubDivisionId in SubDivisionSubMarket SDSM delete from SubMarket SM Where SDSM.SubMarketId=SM.SubMarketId
-- End of Inner nested Loop
FETCH NEXT FROM @mycur1 INTO @test
END
DEALLOCATE @mycur1
------------------------------------------
Here are my three tables I am scripting agains and a description of each.
SubDivision
-----------
SubDivisionId
MarketId
Name
Description
CreatedBy
SubDivisionSubMarket
--------------------
SubDivisionId
SubMarketId
SubMarket
--------------------
SubMarketId
Code
Description
LastUpdateDate
View 2 Replies
ADVERTISEMENT
Sep 26, 2005
Hi all,
I have a temp guy who is doing some work for us (seriously, I never wrote the query).
Now this is the scenario (hold tight). So we have a stored procedure as follows...
ALTER PROCEDURE createSegmentPoints AS
DECLARE @fLat INTEGER
DECLARE @fLon INTEGER
DECLARE @segId INTEGER
-- declare cursor to return the from lat and lon for all segments that do not have address point 109.
DECLARE c1 CURSOR FOR (SELECT From_Latitude, From_Longitude, id AS segment_id FROM Segments WHERE SegmentType != 109)
OPEN c1
FETCH NEXT FROM c1 INTO @fLat, @fLon, @segId
WHILE @@FETCH_STATUS = 0
BEGIN
-- insert into table the segId, from lat, from lon and returned segment id from function.
INSERT INTO test VALUES (@segId,@fLat,@fLon,dbo.points_test(@fLat,@fLon))
FETCH NEXT FROM c1 INTO @fLat, @fLon, @segId
END
CLOSE c1
DEALLOCATE c1
As you can see here I am using a Cursor, which in turn calls a function
with each row that is processed in the recordset. The function that is
called is as follows...
ALTER FUNCTION points_test(@x INTEGER, @y INTEGER)
RETURNS INTEGER
AS
BEGIN
-- function to find the closed segment point with address point 109 to the segment specified in procedure.
DECLARE @tempDistance FLOAT(4)
SET @tempDistance = 1000000
DECLARE @id, @seg, lat, lon INTEGER
DECLARE @distance, @xd, @yd FLOAT
DECLARE c1 CURSOR FOR (SELECT from_latitude, from_longitude, id FROM segments WHERE segmenttype = 109)
OPEN c1
FETCH NEXT FROM c1 INTO @lat, @lon, @id
WHILE @@FETCH_STATUS = 0
BEGIN
-- calucations to get distance.
SET @xd = (@lat-@x)
SET @yd = (@lon-@y)
SET @distance = SQRT((@xd*@xd) + (@yd*@yd))
-- test if you have shortest distance.
IF (@distance < @tempDistance)
BEGIN
SET @tempDistance = @distance
SET @seg = @id
END
FETCH NEXT FROM c1 INTO @lat,@lon, @id
END
CLOSE c1;
DEALLOCATE c1;
RETURN @seg
END
(This function works out an equation to get the shortest distance from
two parameters passed to the function calculated with data from each
row returned within the cursor)
As you can see here, this function contains ANOTHER cursor!! Ouch. The
fact that their is an SQL query in a function is a killer, but having
another embedded cursor there is also a killer - this has virtually
killer the application.
So, how best is it for me to correct this. Should I turn the function
into a stored procudure? But even if I do this, the nested cursor still
remains. I was thinking maybe to have the SQRT equations within the
SELECT expression and then wrapped in a MIN() to maybe get the lowest
value.
Any ideas would be of great help.
Thanks
Tryst
View 2 Replies
View Related
Jun 3, 2004
Morning everyone,
I have a sp that I've created that is to show me everyone table name and column name using nested cursors. However when I execute the procedure it doesn't show me the names, it just tells me the command completed successfully. Here is the code:
CREATE PROCEDURE uspSeeAllViews
AS
SET NOCOUNT ON
DECLARE @strMessageVARCHAR(100)
DECLARE @strColumnVARCHAR(100)
DECLARE @strViewVARCHAR(100)
DECLARE @strCommandVARCHAR(250)
DECLARE crsViews CURSOR FOR
SELECT
name AS strView
FROM
sysobjects
WHERE
type = 'U'
OPEN crsViews
FETCH NEXT FROM crsViews INTO @strView
WHILE @@FETCH_STATUS = 0 BEGIN
DECLARE crsColumns CURSOR FOR
SELECT
name AS strColumn
FROM
syscolumns
WHERE
name = @strView
OPEN crsColumns
FETCH NEXT FROM crsColumns INTO @strColumn
WHILE @@FETCH_STATUS = 0 BEGIN
PRINT @strView + ':' + @strColumn
FETCH NEXT FROM crsColumns INTO @strColumn
END
CLOSE crsColumns
DEALLOCATE crsColumns
FETCH NEXT FROM crsViews INTO @strView
END
CLOSE crsViews
DEALLOCATE crsViews
Thanks for looking, any ideas??
View 7 Replies
View Related
Apr 4, 2008
I have a table like:
Converted_Mortgage_Number Activity_Date Activity_Time Sequence_Number, History_Text
100 2006-01-20 84936 1 Sent a reminder letter
105 2006-01-23 134502 1 Called, but no reply
100 2006 01-24 104532 1 Asked to call again later
100 2006-01-24 104532 2 when it is more convenient
100 2006-01-24 104532 3 and the person I require is available
I wish to concantenate the History_text fields together for records with the same Converted_Mortgage_Number, Activity_Date and Activity_Time so:
100 2006-10-24 104532 Asked to call again later when it is moreconvenient and the person I require is available.
To do this I amusing nested cursors so:
USE ar
GO
DECLARE @mortgage INT,
@date datetime,
@time INT,
@getMortgage CURSOR,
@notes varchar(MAX),
@notesComplete varchar(MAX),
@getDetail CURSOR
SET @getMortgage = CURSOR FOR
SELECT Converted_Mortgage_Number, Activity_Date, Activity_Time
FROM format_history
GROUP BY Converted_Mortgage_Number, Activity_Date, Activity_Time
ORDER BY Converted_Mortgage_Number ASC
OPEN @getMortgage
FETCH NEXT
FROM @getMortgage INTO @mortgage, @date, @time
WHILE @@FETCH_STATUS = 0
BEGIN
SET @notes = ''
SET @getDetail = CURSOR FOR
SELECT History_Text
FROM format_history
WHERE Converted_Mortgage_Number = @mortgage AND Activity_Date = @date AND Activity_Time = @time
ORDER BY Sequence_Number
OPEN @getDetail
SET @notesComplete = ''
FETCH NEXT FROM @getDetail INTO @notes
WHILE (@@FETCH_STATUS = 0)
BEGIN
@notesComplete = @notesComplete + @notes + ' '
FETCH NEXT FROM @getDetail INTO @notes
END
PRINT @notesComplete
CLOSE @getDetail
DEALLOCATE @getDetail
FETCH NEXT
FROM @getMortgage INTO @mortgage, @date, @time
END
CLOSE @getMortgage
DEALLOCATE @getMortgage
GO
But I am getting the error: 'Incorrect syntax near the keyword CLOSE, incorrect syntax near @notesComplete'.
Can anyone please see where I am going wrong?
View 4 Replies
View Related
Aug 24, 2007
What is the best way to nest cursors?
This code does not seem to be returning me all of the data.
Code Snippet
DECLARE element_Cursor CURSOR FOR
SELECT ElementTypeRecNo
FROM dbo.tblTemplateElementType
where TemplateRecno = @TemplateRecNo
OPEN element_cursor
FETCH NEXT FROM Element_Cursor into @ElementTypeRecno
--delete from tblElementCPO
WHILE @@FETCH_STATUS = 0
BEGIN
select @Count = count (*)
from tblProjTypeSet
where ProjRecno = @ProjRecNo
if @Count > 0
begin
select @ProjTypeRecno = ProjTypeRecno
from tblProjTypeSet
where ProjRecno = @ProjRecNo
select @Count = count (*)
FROM dbo.tblElementTypeDep
where TemplateRecno = @TemplateRecNo
and ProjTypeRecno = @ProjTypeRecNo
if @Count > 0
begin
DECLARE ElementTypeDep_Cursor CURSOR FOR
SELECT ElementTypeDepRecNo, PreElementTypeRecNo,
PostElementTypeRecNo, ElapsedTimeDueDates, ElapsedTimePlanDates,
Description
FROM tblElementTypeDep
WHERE (TemplateRecNo = @TemplateRecNo)
AND (ProjTypeRecNo = @ProjTypeRecno)
AND (PreElementTypeRecNo = @ElementTypeRecno)
OPEN ElementTypeDep_cursor
FETCH NEXT FROM ElementTypeDep_Cursor
into @ElementTypeDepRecno, @PreElementTypeRecNo,
@PostElementTypeRecno, @ElapsedTimeDueDates, @ElapsedTimePlanDates,
@Description
WHILE @@FETCH_STATUS = 0
BEGIN
select @PreElementRecNo = ElementRecno
from tblElementCPO
where ProjRecNo = @ProjRecNo
and IssueRecno = @IssueRecNo
and ElementTypeRecno = @PreElementTypeRecno
if @PreElementRecno is not null
begin
select @PostElementRecNo = ElementRecno
from tblElementCPO
where ProjRecNo = @ProjRecNo
and IssueRecno = @IssueRecNo
and ElementTypeRecno = @PostElementTypeRecno
if @PostElementRecno is not null
begin
select @Count = count (*)
from tblElementDepCPO
where ElementTypeDepRecno = @ElementTypeDepRecno
and PreElementRecNo = @PreElementRecNo
and PostElementRecno = @PostElementRecno
if @Count = 0
begin
INSERT INTO tblElementDepCPO
(ElementTypeDepRecNo, PreElementRecNo,
PostElementRecNo, ElapsedTimeDueDates,
ElapsedTimePlanDates, Description,
ChangeDate, ChangePerson)
VALUES (@ElementTypeDepRecno, @PreElementRecNo,
@PostElementRecno, @ElapsedTimeDueDates,
@ElapsedTimePlanDates, @Description,
GETDATE(), CURRENT_USER)
end
select @Count = count (*)
from tblElementAttemptCPO
where ElementRecNo = @PostElementRecNo
if @Count = 0
begin
select @Count = count (*)
from tblElementAttemptCPO
where ElementRecNo = @PostElementRecNo
if @Count = 0
begin
select @NextPlanDate = ProjectedCompletionDate,
@NextDueDate = RequiredCompletionDate
from tblElementAttemptCPO
where ElementRecno = @PreElementRecNo
end
else
begin
select @NextPlanDate = @StartDate
select @NextDueDate = @StartDate
end
select @NextPlanDate =
dbo.fncAddBusinessDays (@NextPlanDate, @ElapsedTimePlanDates)
select @NextDueDate =
dbo.fncAddBusinessDays (@NextDueDate, @ElapsedTimePlanDates)
insert into tblElementAttemptCPO (ElementRecno,
ProjectedCompletionDate, RequiredCompletionDate,
ProjectedStartDate, RequiredStartDate,
ActualStartDate, ActualCompletionDate, AttemptNum,
IsCompleted, IsStarted, ResponsibleRoleTypeRecno,
ChangeDate, ChangePerson)
values (@PostElementRecno,
@NextPlanDate, @NextDueDate,
'1/11/1900', '1/11/1900',
'1/11/1900', '1/11/1900', 0,
0, 0, 0,
GETDATE(), CURRENT_USER)
end
end
end
FETCH NEXT
FROM ElementTypeDep_Cursor
into @ElementTypeDepRecno, @PreElementTypeRecNo,
@PostElementTypeRecno, @ElapsedTimeDueDates, @ElapsedTimePlanDates,
@Description
END
CLOSE elementTypeDep_Cursor
DEALLOCATE elementTypeDep_Cursor
end
FETCH NEXT FROM element_Cursor into @ElementTypeRecno
END
CLOSE element_Cursor
DEALLOCATE element_Cursor
end
View 2 Replies
View Related
Jul 1, 2004
I am not getting any error message. It just hangs...
Any idea what I am missing....
******************
ALTER PROCEDURE TrigSendPreNewIMAlertP2
@REID int
AS
Declare @RRID int
Declare @ITID int
Declare @FS1 int
Declare @FS2 int
Declare crReqRec cursor local for
select RRID from RequestRecords where REID = @REID and RRSTatus = 'IA' and APID is not null
open crReqRec
fetch next from crReqRec into @RRID
set @FS1 = @@Fetch_Status
while @FS1 = 0
Begin
Declare crImpGrp cursor local for
select ITID from RequestRecords where RRID = @RRID
open crImpGrp
fetch next from crImgGrp into @ITID
set @FS2 = @@Fetch_Status
while @FS2 =0
Begin
EXEC TrigSendNewIMAlertP2 @ITID
FETCH next from crImpGrp into @ITID
end
FETCH next from crReqRec into @RRID
end
close crImpGrp
deallocate crImpGrp
close crReqRec
deallocate crReqRec
View 1 Replies
View Related
Dec 11, 2000
All,
I have a question on a nested Cursor statement, I am having problem getting the @@Fetch_Status to work correctly...
I can get the first cursor to fetch and the the second cursor to fetch all of it rows but when it reaches the end. It should fetch the first cursors next row and @@fetch_Status should be 0.
Is there a way around this???
Thanks,
~Lee
Alter Procedure Summary As
Declare @DateID nvarchar(50)
Declare @ShortDate nvarchar(30)
Declare @SourceIPID nvarchar(50)
Declare @SourceIP nvarchar(30)
Declare @Packets int
Declare lead_cur CURSOR FOR
SELECT tbl_Date.DateID, tbl_Date.ShortDate FROM Tbl_Date WHERE NOT tbl_date.shortdate = convert(char(11),GetDate())
FOR READ ONLY
Declare lead_cur2 CURSOR FOR
SELECT SourceIPID, SourceIP FROM tbl_SrcIP
FOR READ ONLY
Open lead_cur
Open lead_cur2
FETCH NEXT FROM lead_cur INTO @DateID,@ShortDate
While @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM lead_cur2 INTO @SourceIPID, @SourceIP
While @@FETCH_STATUS = 0
BEGIN
Set @Packets = (Select ISNULL(Sum(CAST(strNumPackets As Int)),0)
FROM tbl_All_SysDATA
Where DateID = @DateID and SourceIPID = @SourceIPID)
If @packets > 0
Insert tbl_SysIPSummary (DateID,IPID,Packets) VALUES (@DateID,@SourceIPID,@Packets)
FETCH NEXT FROM lead_cur2 INTO @SourceIPID, @SourceIP
END
FETCH NEXT FROM lead_cur INTO @DateID,@ShortDate
END
Close lead_cur
Close lead_cur2
DEALLOCATE lead_Cur
DEALLOCATE lead_Cur2
GO
View 1 Replies
View Related
Dec 4, 2007
I have a Master/Detail table setup - let's call the master "Account" and the detail "Amount". I also have a "black box" stored procedure (BlackBox_sp) which carries out a lot of complex processing.
What I need to do is, for each Account, I need to iterate thtough it's Amount records and call the black box each time. Once I've finished going through all the Amount records, I need to call the black box again once for the Account. This must be done with the Account & Amount rows in a specific order.
So I have something along the lines of
Code Block
DECLARE Total int
DECLARE Account_cur
OPEN Account_cur
FETCH NEXT FROM Account_cur
WHILE FETCH_STATUS = 0
BEGIN
SET Total = 0
DECLARE Amount_cur
OPEN Amount_cur
FETCH NEXT FROM Amount_cur
WHILE FETCH_STATUS = 0
BEGIN
SET Total = Total + Amount
EXEC BlackBox_sp (Amount)
END
CLOSE Amount_cur
EXEC BlackBox_sp (Total)
END
CLOSE Account_cur
Any tips on another approach would be appreciated given the contraints I have.
Greg.
View 1 Replies
View Related
May 15, 2015
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
[code]...
View 7 Replies
View Related
Apr 17, 2008
i want to store the output in out variable .Which gives multiple values.
create procedure usp_test (@AccountID INT)
as
begin
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID
end
i get nearly ten rows in the print statement
how can i assign the output to a out variable where i get all ten rows.
Any ideas or suggestions.
View 1 Replies
View Related
Feb 21, 2007
Hi below is the code I am using.------------------------------------SET NOCOUNT ONDECLARE @emailid varchar(50), @rastype varchar(50),@message varchar(80)declare @allrastypes varchar(200)DECLARE email_cursor CURSOR FORSELECT distinct EmailFROM dbo.tblMaintCustomerORDER BY EmailOPEN email_cursorFETCH NEXT FROM email_cursorINTO @emailidWHILE @@FETCH_STATUS = 0BEGINPRINT ' 'SELECT @message = 'Email Address ' +@emailidPRINT @message-- Declare an inner cursor based-- on vendor_id from the outer cursor.DECLARE rastype_cursor CURSOR FORSELECT distinct [RasType]FROM dbo.tblMaintCase x, dbo.tblMaintCustomer yWHERE x.caseid = y.caseid ANDy.Email = @emailidand RasType is not nullOPEN rastype_cursorFETCH NEXT FROM rastype_cursor INTO @rastypeselect @allrastypes = @allrastypes + ',' + @rastypeIF @@FETCH_STATUS <0PRINT ' <<None>>'WHILE @@FETCH_STATUS = 0BEGINSELECT @message = @rastypePRINT @messageselect @allrastypes = @allrastypes + ',' + @rastypeFETCH NEXT FROM rastype_cursor INTO @rastypeENDCLOSE rastype_cursorDEALLOCATE rastype_cursorinsert into dbo.tblTest values(@emailid,@allrastypes)select @allrastypes = ''FETCH NEXT FROM email_cursorINTO @emailidENDCLOSE email_cursorDEALLOCATE email_cursor--------------------------------------I basically want the value of @allrastypes to accumulate each time itloops through, which is is not doing.The result I get is :Email Address Join Bytes!G5R(for here i want @allrastypes to be 'G5R,')Email Address Join Bytes!G1G3G5O(for here i want @allrastypes to be 'G1,G3,G5O')Can someone helpThanksArchana
View 1 Replies
View Related
Oct 3, 2006
Hi all.
I am stuck in a bit of a conundrum for quite a while now, and I hope someone here will help me figure this one out.
So, first things first: let me explain what I need to do. I am
designing a web application that will allow users to consult info
available in a SQL2000 database. The user will enter the search
criterea, and hopefully the web page will show matching results.
The problem is the results shown aren't available per se in the DB, I
need to process the data a bit. I decided to do so on the SQL Server
side, though the use of cursors. So, when a user defines his search
criteria, I run a stored procedure that begins by building a dynamic
sql query and creating a cursor for it. I used a global cursor in order
to do so. It looked something like this:
SET @sqlQuery = ... (build the dinamic sql query)
SET @cursorQuery = 'DECLARE myCursor CURSOR GLOBAL FAST_FORWARD FOR ' + @sqlQuery
EXEC @cursorQuery
OPEN myCursor
FETCH NEXT FROM myCursor INTO ...
CLOSE myCursor
DEALLOCATE myCursor
This works fine, if there's only one instance of the
stored procedure running at a time. Should another user connect to the
site and run a search while someone's at it, it'll fail due to the
atempt to create a cursor with the same name.
My first thought was to make the cursor name unique, which led me to:
...
SET @cursorName = 'myCursor' + @uniqueUserID
SET @cursorQuery = 'DECLARE '+ @cursorName + 'CURSOR FAST_FORWARD FOR ' + @sqlQuery
EXEC @cursorQuery
...
The problem with this is that I can't do a FETCH NEXT FROM @cursorName since
@cursorName is a char variable holding the cursor name, and not a
cursor variable. So to enforce this unique name method the only option
I have is to keep creating dynamic sql queries and exucting them. And
this makes the sp a bitch to develop and maintain, and I'm guessing it
doesn't make it very performant.
So I moved on to my second idea: local cursor variables. The problem with
this is that if I create a local cursor variable by executing a dynamic
query, I can't extract it from the EXEC (or sp_executesql) context, as
it offers no output variable.
I guess my concrete questions are:
Is it possible to execute a dynamic sql query and extract a (cursor) variable from it?Is it possible to populate a local cursor variable with a global cursor, by providing the global cursor's name?Can I create a local cursor variable for a dynamic sql query? How?
Anybody sees another way arround this?Thanks in advance,
Carlos
View 3 Replies
View Related
Jul 20, 2005
I am trying to write a utility/query to get a report from a table. Belowis the some values in the table:table name: dba_daily_resource_usage_v1conn|loginame|dbname|cum_cpu|cum_io|cum_mem|last_b atch------------------------------------------------------------80 |farmds_w|Farm_R|4311 |88 |5305 |11/15/2004 11:3080 |abcdes_w|efgh_R|5000 |88 |4000 |11/15/2004 12:3045 |dcp_webu|DCP |5967 |75 |669 |11/16/2004 11:3095 |dcp_webu|XYZ |5967 |75 |669 |11/17/2004 11:30I need to write a query which for a given date (say 11/15/2004),generate a resource usage report for a given duration (say 3 days).Here is my query:************************************set quoted_identifier offdeclare @var1 intset @var1=0--BEGIN OUTER LOOPwhile @var1<=3 --INPUT runs the report for 3 daysbegindeclare @vstartdate char (10) --INPUT starting dateset @vstartdate='11/15/2004'--builds a range of datedeclare @var2 datetimeset @var2=(select distinct (dateadd(day,@var1,convert(varchar(10),last_batch,101)))--set @var2=(select distinct (dateadd(day,@var1,last_batch))from dba_daily_resource_usage_v1where convert(varchar (10),last_batch,101)=@vstartdate)set @var1=@var1+1 --increments a daydeclare @var5 varchar (12)--set dateformat mdy--converts the date into 11/15/2004 format from @var2set @var5="'"+(convert(varchar(10),@var2,101))+"'"--print @var5 produces '11/15/2004' as resultdeclare @vloginame varchar (50)declare @vdbname varchar (50)--BEGIN INNER LOOPdeclare cur1 cursor read_only forselect distinct loginame,dbname fromdba_daily_resource_usage_v1where convert(varchar (10),last_batch,101)=@var5--??????PROBLEM AREA ABOVE STATEMENT??????--print @var5 produces '11/15/2004' as result--however cursor is not being built and hence it exits the--inner loop (cursor)open cur1fetch next from cur1 into @vloginame, @vdbnamewhile @@fetch_status=0begin--print @var5 produces '11/15/2004' as resultdeclare @vl varchar (50)set @vl="'"+rtrim(@vloginame)+"'"declare @vd varchar (50)set @vd="'"+@vdbname+"'"--processes the cursorsdeclare @scr varchar (200)set @scr=("select max(cum_cpu) from dba_daily_resource_usage_v1 whereloginame="+@vl+" and dbname="+@vd+" and "+"convert(varchar(10),last_batch,101)="+@var5)--set @var3 =(select max(cum_cpu) from dba_daily_resource_usage_v1where--loginame=@vloginame and dbname=@vdbname--and convert(varchar (10),last_batch,101)=@var5)print @scr--exec @scrfetch next from cur1 into @vloginame, @vdbnameend--END INNER LOOPselect @var2 as "For date"deallocate cur1end--END OUTER LOOP************************************PROBLEM:Even though variable @var5 is being passed as '11/15/2004' inside thecursor fetch (see print @var5 inside the fetch), the value is not beingused to build the cursor. Hence, the cursor has no row set.Basically, the variable @var5 is not being processed/passed correctlyfrom outside the cursor to inside the cursor.Any help please.Thanks*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View 3 Replies
View Related
Jan 22, 2007
We are trying to create a model of linear regression with nested table. We used the create mining model sintax as follow :
create mining model rate_plan3002_nested2
( CUST_cycle LONG KEY,
VOICE_CHARGES double CONTINUOUS predict,
DUR_PARTNER_GRP_1 double regressor CONTINUOUS ,
nested_taarif_time_3002 table
( CUST_cycle long CONTINUOUS,
TARIFF_TIME text key,
TARIFF_VOICE_DUR_ALL double regressor CONTINUOUS
)
) using microsoft_linear_regression
INSERT INTO MINING STRUCTURE [rate_plan3002_nested2_Structure]
(CUST_cycle ,
VOICE_CHARGES ,
DUR_PARTNER_GRP_1 ,
[nested_taarif_time_3002](SKIP,TARIFF_TIME ,TARIFF_VOICE_DUR_ALL)
)
SHAPE {
OPENQUERY([Cell],
'SELECT CUST_cycle ,
VOICE_CHARGES ,
DUR_PARTNER_GRP_1
FROM dbo.panel_anality_3002
order by CUST_cycle ')}
APPEND
({OPENQUERY([Cell],
'select CUST_cycle,
TARIFF_TIME,
CYCLE_DATE
from dbo.nested_taarif_time_3002
order by CUST_cycle,TARIFF_TIME')
}
relate CUST_cycle to CUST_cycle
) as nested_taarif_time_3002
The results we got are a model with intercept only. if we don't use the nested variable (the red line) we get a rigth model . (we had more variable ....)
Is there a way to do this regression correctly?
Thanks,
Dror
View 7 Replies
View Related
Sep 24, 2015
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.
View 4 Replies
View Related
Aug 21, 2007
All:
I am trying to code the following SQL into an OLEDB data source but it is not allowing me to do so because I think the variables are nested in multiple SQL statements. I have seen other posts that suggest using a variable to store the SQL but I am not sure how it will work.
I would also like to mention that the OLEDB source executes from within a For Each loop that is actually passing the values for the variables, which was one of the reasons I got stumped on how I could have a variable store the SQL.
Here is the SQL:
select b.ProgramID, b.ProductCode, b.BuyerID, b.Vendor,sum(a.Ordered) As Qty_Pruchased
From SXE..POLine a INNER JOIN
(SELECT VIR_Program.ProgramID, VIR_ActiveSKU.ProductCode, VIR_ActiveSKU.BuyerID, Vendor
FROM VIR_Program INNER JOIN
VIR_ActiveSKU ON VIR_Program.ProgramID = VIR_ActiveSKU.ProgramID
INNER JOIN Vendor ON VIR_Program.VendorID = Vendor.VendorID
WHERE ProgramFreq=?) b
ON a.ProductCode = b.ProductCode
WHERE a.TransDate >=? AND
a.TransDate ?
Group By b.ProgramID, b.ProductCode, b.BuyerID, b.Vendor
Thanks!
View 5 Replies
View Related
Nov 15, 2007
do i need to nest a query in RS if i want a calculated column to be compared against a multi value variable? It looks like coding WHERE calcd name in (@variable) violates SQL syntax. My select looked like
SELECT ... ,CASE enddate WHEN null then 1 else 0 END calcd name
FROM...
WHERE ... and calcd name in (@variable)
View 1 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
Apr 14, 2000
Please help resolve a problem (and debate!).
We have an app using VB with Access as the front end to SQL. SQL statments were built and sent
directly to the server obtaining set-oriented results. Response was fair.
We have a new app developed by an "expert" using VB & Interdev that was to be ported for use on
the internet. The app was designed using the same logic to build the SQL statements, but it is also
using cursors to retrieve all data. RESPONSE IS TERRIBLE!
The designer says that to access SQL over the Web, cursor use is a MUST!
True? Not True?
If true, and I am stuck with an app using cursors, any basic suggestions on where to look to improve
response time?
Thanks for any input.
FJ
View 1 Replies
View Related
Apr 23, 1999
Hi,
I am using SQL Server 6.5 and I have a VB routine that updates a field in a tble so it can be used in a primary key. This is run after input of data using bcp. I have noticed on several posts re: using cursors to move through a recordset and was wondering if I could use this functionality to replace my VB routine. I checked the archives and found several messages but I am not sure where to start. My VB routine is:
I first would query the data to return all rows where the value of R08SegmentValue= Null. Then I move through the resultset changing the value of the field R08Segments.
***********************Start of VB Code****************
'Set initial value for sTReportHeaderIdx
With rs1
sTReportHeaderIdx = !ReportIdx & !HeaderIdx
sPReportHeaderIdx = sTReportHeaderIdx
End With
bCount = 1
'loop through rs and when streportheaderidx changes reset bCount to 1
'otherwise increment bcount by 1 and write to field R08SegmentValue
Do While rs1.EOF = False And blnContinue = True
DoEvents
Do While sPReportHeaderIdx = sTReportHeaderIdx
With rs1
.Edit
!R08SegmentValue = bCount
.Update
bCount = bCount + 1
sPReportHeaderIdx = sTReportHeaderIdx
.MoveNext
If Not rs1.EOF Then sTReportHeaderIdx = !ReportIdx & !HeaderIdx
End With
Loop
sPReportHeaderIdx = sTReportHeaderIdx
bCount = 1
Loop
In the end my data should look like
ReportIdx HeaderIdx R08SegmentValue
1 1 1
1 1 2
2 1 1
2 1 2
2 1 3
3 1 1
3 1 2
3 1 3
1 2 1
1 2 2
1 2 3
etc..
Can this be done via an sp? How would I go about writing something like this?
Thanks in advance...any assistance you could provide would be appreciated!
Kevin
View 1 Replies
View Related
Aug 6, 2002
I hope someone can help me with this, as BOL didn't get me the answer I am looking for.
I want to write an update step that will transform the following:
1 abc
1 def
2 lmn
3 rst
4 tuv
4 xyz
4 jkl
5 pqr
into this:
1 abc,def
2 lmn
3 rst
4 tuv,xyz,jkl
5 pqr
In other words, I want to concatenate multiple instances into 1 record per row, but I am not familiar with working with cursors or loops.
Thanks in advance!
bv
View 1 Replies
View Related
Nov 16, 1998
According go textbooks and T-SQL developers experience - using cursors is not recommended, more over they say: avoid cursors where it's possible.
Could someone please recommend any other way to go through the recordset(resultset) forward and backward to perform some search or calculations, if there are a specific requirement for not using front-end tools such as VB or MS Access(please don't ask why), other words - all the work must be performed in T-SQL stored procedure.
Thanks
View 3 Replies
View Related
Feb 24, 2008
Hi
I defined a cursor and executed it...but now i exactly forgot what select statement i had run in the cursor..(forgot the columns that i am extracting )
how do I view the contents of the cursor ?
View 1 Replies
View Related
Aug 25, 2004
I have a stored proc that merges records from an undeduped table to a deduped table. It is running really slowly. Merging 70 million records against a deduped 70 million is taking 115 hours and counting on decent hardware. Very slow.
I suspect there is significant room for optimization here. Some of my ideas:
- Write/update back to the cursor rather than executing separate UPDATE statements.
- Try a dynamic cursor instead of a READ ONLY cursor.
- Dump new elements to a separate table or a file and then do a single large INSERT.
Anyone else think any of these ideas will work? Can anyone think of something better?
BTW, I've tried to replaced the procedural cursor code with set based UPDATES/INSERTS but the short version of the story is that that route just didn't pan out. I know that is very common optimization advice.
I've made minor simplifications to the code:
- Took out code to handle last line
- Took out progress logging code
- Removed some DECLARE statements. These are needed to run but it should be obvious what they were supposed to be.
View 10 Replies
View Related
Aug 27, 2004
Trying to understand cursors a little better, found this in one of the dbs I inherited. Just trying ot figure out why they put it there cause no one else knows anything about it.
DECLARE [TM #] CURSOR
FOR SELECT * FROM [2004 TERMS];
View 10 Replies
View Related
Jan 14, 2005
nevermind forget I asked thanks anyways
View 11 Replies
View Related
Feb 10, 2005
These guys I work with have some sql scripts they run over night and they bog down the server and the machine will be gummed up in the morning etc..
Well, I finally looked at this processing and the culprit is cursors. And cursors within cursors. I would like to just get some opinions about what would be more processor efficient so I can send my boss a link to this thread.
Using a cursors to pull records and update them.
vs
Create script using a scripting language that pulls the records through ADO, loops through them and performs updates as necessary using update statements and the like.
Be nice. I have to work with these guys.
View 9 Replies
View Related