Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





How Get The Dynamic Sql In To Cursor


Dear folks,

In My Query i am using where in condition .It return multiple record .I want store it in to cursor and perform the operation.

Declare @sql varchar(5000);
set @sql='select * from Role where Role_id in('+ @role_ids +')';
Exec @sql;

I want take this record set in to cursor .How to do it.
please help me.




View Complete Forum Thread with Replies

Related Forum Messages:
Dynamic Cursor Versus Forward Only Cursor Gives Poor Performance
Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin

View Replies !
Dynamic Cursor/ Dynamic SQL Statement
I've looked up Books Online on Dynamic Cursor/ Dynamic SQL Statement.

Using the examples given in Books Online returns compilation errors. See below.

Does anyone know how to use Dynamic Cursor/ Dynamic SQL Statement?

James



-- SQL ---------------

EXEC SQL BEGIN DECLARE SECTION;
char szCommand[] = "SELECT au_fname FROM authors WHERE au_lname = ?";
char szLastName[] = "White";
char szFirstName[30];
EXEC SQL END DECLARE SECTION;

EXEC SQL
DECLARE author_cursor CURSOR FOR select_statement;

EXEC SQL
PREPARE select_statement FROM :szCommand;

EXEC SQL OPEN author_cursor USING :szLastName;
EXEC SQL FETCH author_cursor INTO :szFirstName;



--Error--------------------
Server: Msg 170, Level 15, State 1, Line 23
Line 23: Incorrect syntax near ';'.
Server: Msg 1038, Level 15, State 1, Line 24
Cannot use empty object or column names. Use a single space if necessary.
Server: Msg 1038, Level 15, State 1, Line 25
Cannot use empty object or column names. Use a single space if necessary.
Server: Msg 170, Level 15, State 1, Line 27
Line 27: Incorrect syntax near ';'.
Server: Msg 170, Level 15, State 1, Line 30
Line 30: Incorrect syntax near 'select_statement'.
Server: Msg 170, Level 15, State 1, Line 33
Line 33: Incorrect syntax near 'select_statement'.
Server: Msg 102, Level 15, State 1, Line 35
Incorrect syntax near 'author_cursor'.
Server: Msg 170, Level 15, State 1, Line 36
Line 36: Incorrect syntax near ':'.

View Replies !
Dynamic SQL In Cursor
I need to pass a list of values into a cursor as such...


DECLARE
@group_SQL varchar(255)

SET @group_SQL = 'SELECT group_id FROM groups where group_id in (' + @group_id + ')'

DECLARE groupContact_import_cursor CURSOR
FOR EXEC(@group_SQL)
OPEN groupContact_import_cursor
FETCH NEXT FROM groupContact_import_cursor INTO @group_id
WHILE (@@FETCH_STATUS = 0)
BEGIN
insert into groupContacts (group_id, contact_id) values (@group_id, @new_cid)
FETCH NEXT FROM groupContact_import_cursor INTO @group_id
END
CLOSE groupContact_import_cursor
DEALLOCATE groupContact_import_cursor

But MS SQL doesn't seem to like the FOR EXEC(@group_SQL). Can someone shed some light?

TIA

View Replies !
Dynamic Cursor
I am trying to use a dynamic cursor in a stored procedure:
The code looks like this :


/************************************************** ***
set @sFormula = 'Monthlyformula'
set @sStartDate = '02/01/2004'
set @sEndDate = '02/01/2004'


exec('DECLARE APPGRIDROWS_METRICS CURSOR FOR select populateid From appgridrows where histdisplaygrid = 3 And '+ @sFormula +' Is Null and exists (SELECT 1 From PAYROLL_DATA_PERIOD as h Where h.id=1 and h.populateid=appgridrows.populateid and h.StartDate between '+ @sStartDate +' and '+ @sEndDate +')' )
/************************************************** ***

And this is what it is interpreting

select populateid From appgridrows where histdisplaygrid = 3 And Monthlyformula Is Null and exists (SELECT 1 From PAYROLL_DATA_PERIOD as h Where h.id=1 and h.populateid=appgridrows.populateid and h.StartDate between 02/01/2004 and 02/01/2004)

My problem is Is there anyway that I can put the quotes before those dates('02/01/2004') so that my cursor has some records returned

Thanks in advance

SK

View Replies !
Dynamic Cursor
Hello !

I´m having a big problem with a dynamic cursor.
There is my problem:

I have two cursors. One I use to select a master table. The other I use to select a detail table. I want to fetch all rows of the master and for each row select the details.

How can I pass to the detail cursor the master key ?

Thanks and I´m sorry for my poor English ! :)

View Replies !
Dynamic Cursor
Hi All€¦
 
I need to bind a DataGrid to server dynamic cursor.
 
Please help!

View Replies !
Dynamic Cursor Generation..
Hi Everybody,I have a probs with dynamic generation.I am writing the probs======================================create proc testasdeclare @query varchar(500)set @query = 'select * from table'----------------------------------------------declare mycur Cursor for Select * from table |open mycur |----------------------------------------------but instate of above block how can I dynamically generate this query?---------------------------------------declare mycur Cursor for exec (@query) |---------------------------------------Or tell me the way.RegardsArijit Chatterjee

View Replies !
Declare Cursor With Dynamic SQL?
Hello..

Can you declare a cursor with dynamic SQL?

I have a situation where the SQL for my cursor MUST be assembled in a buffer, but I cannot get the cursor declaration to accept my buffer as the SQL statement.

these attempts did not work:

DECLARE crsCursor CURSOR FOR @vchrSQL
DECLARE crsCursor CURSOR FOR (@vchrSQL)

Does anybody know if you definitely can or definitely cannot use dynamic SQL with cursors?

View Replies !
Dynamic Select For CURSOR
Hi all

I am trying to do dynamic Select for Cursor. The dynamic would be like this:
IF CONDITION1 IS TRUE:
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE CustomerTenderID = @CustomerTenderID
IF CONDITION2 IS TRUE:
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE CustomerTenderID = @CustomerTenderID AND
CustomerSiteID = @CustomerSiteID

etc etc

Here's the cursor


DECLARE RateList CURSOR FOR
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE (BASED ON CONDITION)
ORDER BY CustomerTenderID,
CustomerSiteID,
SupplierID,
ContractPeriod

OPEN RateList
FETCH NEXT FROM RateList
INTO@CustomerTenderID, @ReturnedCustomerSiteID, @ReturnedContractPeriod, @ReturnedSupplierID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @rowNum = @rowNum + 1

-- DO SOME FUNKY STUFF


FETCH NEXT
FROM RateList
INTO@CustomerTenderID, @ReturnedCustomerSiteID, @ReturnedContractPeriod, @ReturnedSupplierID

View Replies !
Declare Dynamic Cursor From String
Hi,is it possible to create a cursor from a dynamic string?Like:DECLARE @cursor nvarchar(1000)SET @cursor = N'SELECT product.product_idFROM product WHERE fund_amt > 0'DECLARE ic_uv_cursor CURSOR FOR @cursorinstead of using this--SELECT product.product_id--FROM product WHERE fund_amt > 0 -- AND mpc_product.status= 'aktiv'Havn't found anything in the net...Thanks,Peppi

View Replies !
Dynamic Cursor - Sorting In Declaration
Hello everybody!I have a small table "ABC" like this:id_position | value---------------------------1 | 112 | 223 | 33I try to use a dynamic cursor as below.When the statement "order by id_position" in declare part of the cursor_abcis omitted - cursor work as it should.But when the statement "order by id_position" is used, cursor behave asstatic one.What's the matter, does anybody know?Code:declare @id_position as int, @value as intDECLARE cursor_abc CURSORFORselect id_position, value from abcorder by id_positionset nocount onopen cursor_abcFETCH NEXT FROM cursor_abcINTO @id_position, @valueWHILE @@FETCH_STATUS = 0BEGINprint @id_positionprint @valueprint '----------------------------'update abc set value=666 --next reading should give value=666FETCH NEXT FROM cursor_abcINTO @id_position, @valueENDCLOSE cursor_abcDEALLOCATE cursor_abcGORegardsLucas

View Replies !
Dynamic Execution Of Cursor Fetch
I'm trying to write code which will fetch records from a dynamically created cursor. Therefore the cursor name is not known at design time.

Unfortunately applying an enclosing the fetch command in quotes and then calling the execute method with this string will not work.

e.g.

declare @A varchar(10),
@B varchar(10),
@sFetch varchar(255)

--Open the cursor
Execute ('Open ' + crAnyCursor)

--create fetch string
Select @sFetch = 'Fetch Next From' + crAnyCursor + 'into @A, @B'

execute (@sFetch)

The following error is returned...
Msg 137, Level 15, State 1
Must declare variable '@A'.

Is there another means of working with dynamically executed cursors?

Thanks
JohnG

View Replies !
Dynamic Cursor In Stored Procedure
when i try to compile the following sp, i get an error Line 11:Incorrect syntax near;. Can someone please tell me what i am doing wrong. thanks a lot.

CREATE PROCEDURE test_dump (@p_query nvarchar(4000)) AS
declare

@cmdtxt as varchar(4000),
@SQLString NVARCHAR(4000),
@SQLString1 NVARCHAR(4000),
@pid varchar(22),
@lname varchar(60)
begin

EXEC SQL BEGIN DECLARE SECTION;

char prep[] = @p_query;

EXEC SQL END DECLARE SECTION;

EXEC SQL PREPARE prep_stat FROM :prep;

EXEC SQL DECLARE contact_crsr CURSOR FOR prep_stat;



OPEN contact_crsr
FETCH NEXT FROM contact_crsr
INTO @pid, @lname


-- Check @@FETCH_STATUS to see if there are any more rows to fetch.

WHILE @@FETCH_STATUS = 0

BEGIN

SET @SQLString1 = 'HELLO ' + @pid + ' ' + @lname
select @cmdtxt = "echo " + @SQLString1 + " >> c:empmyfile.txt"
exec master..xp_cmdshell @cmdtxt

FETCH NEXT FROM contact_crsr

INTO @pid, @lname

END



CLOSE contact_crsr

DEALLOCATE contact_crsr


end

View Replies !
Executing SP Having A Dynamic Cursor Fails In Calling SP
Hi,
In a stored procedure (SP1) I call another stored procedure (SP2), passing along parameters. In SP2 I dynamically build cursor c1. I can execute SP2 without any problems but when I start SP1 I get the following message:

Msg 16916, Level 16, State 1, Procedure SP2, Line 114
A cursor with the name 'C1' does not exist.

Yes, the cursor is of type GLOBAL. I am sure I miss something here ...
Any help is highly appreciated !

Thanks: Peter

View Replies !
Declare Cursor Based On Dynamic Query
Hi,

I am declaring the cursor based on a query which is generated dynamically. but it is not working

 

Declare @tempSQL varchar(1000)

--- This query will be generated based on my other conditon and will be stored in a variable

set @tempsql = 'select * from orders'

declare cursor test for @tempsql

open test

 

This code is not working.

 

please suggest

 

Nitin

View Replies !
Make A Dynamic Cursor In A Stored Procedure
I need im my aplication to meke a "Cursor" in a execution of a stored procedure.

For sample:

In a table with a report definition I have the "Fileds, From, Group, Order " clausulas and  I need make a cursor with  a contents of this fileds.

How can I do ???

My code:

Declare @idRelat int, @cmd_FROM nvarchar(1024), @cmd_Det nvarchar(50)
SELECT @idRelat = idRelat, @cmd_Det = cmd_DET
FROM Relatórios WHERE Nome = @p_Relat

Declare @Tot_Col smallint, @Tot_Lin smallint, @Campos smallint,
  @Aux_Select nvarchar(1024), @Aux_Group nvarchar(1024), @Aux_Order nvarchar(1024)

Select @Tot_Col = 0
Select @Tot_Lin = 0
Select @Campos = 0
Select @Aux_Select = "SELECT " + @cmd_DET + "AS Soma"
Select @Aux_Group = "GROUP BY "
Select @Aux_Order = "ORDER BY "
Declare @a_Local char(1), @a_Linha smallint, @a_Campo nvarchar(50)
Declare cur_Aux insensitive cursor for
  SELECT Local, Linha, Campo
  From Relatórios_Margens
  WHERE (idRelat = @idRelat)
  ORDER BY Local, Linha
Open cur_Aux
Fetch cur_Aux into @a_Local, @a_Linha, @a_Campo
While @@FETCH_status = 0 begin
  If @a_Local = "C"
    Select @Tot_Col = @Tot_Col + 1
  Else
    Select @Tot_Lin = @Tot_Lin + 1
  Select @Campos = @Campos + 1
  If @Aux_Group <> "GROUP BY " begin 
    Select @Aux_Group = @Aux_Group + ", "
  If @Aux_Order <> "ORDER BY " begin 
    Select @Aux_Order = @Aux_Order + ", "
  Select @Aux_Select = sSelect + ", " + @a_Campo + " AS Campo" + @Campos
  Select @Aux_Group = @Aux_Group + @a_Campo
  Select @Aux_Order = @Aux_Order + @a_Campo
  Fetch cur_Aux into @a_Local, @a_Linha, @a_Campo
End
Select @Aux_Select = @Aux_Select
-- <<<< MONTA COMANDO SQL
Select @Aux_Select = @Aux_Select + " " + @cmd_FROM + " " + @p_Filtro + " " + @Aux_Group + " " + @Aux_Order
Declare @Cursor_Aux cursor
Set @Cursor_Aux = cursor for @Aux_Select
Open @Cursor_Aux

Not working !!!!

 

View Replies !
Dynamic Query, Local Cursor Variable And Global Cursors
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 Replies !
Using A &"dynamic Top&" Statement With A Cursor
Help please,Have a situation when converting from Oracle SP's to SQL SP's. The oldoracle cursor was roughly as followsCURSOR cur_rsStock ISselect*from(select StockRowId, CategoryIdfromSTOCKDISPOSABLEwhereSTOCKDEFID=numDefIdORDER BYSTOCKROWID)whereROWNUM <= numQuantity;The closest I can get in MS SQL is as follows :declare cur_rsStockCURSOR forselect top @numQuantityStockRowId, CategoryIdfromSTOCKDISPOSABLEwhereSTOCKDEFID=numDefIdORDER BYSTOCKROWIDBut, SQL doesn't allow variables next to top. I know I can assign the wholeselect statement to a string and use exec to exec the string to get arecordset but how can I point a cursor to receive its output?i.e.set @strSQl = select top ' + @numQuantity + ' StockRowId, CategoryId.......exec @strSQLbut how do I dodeclare cur_rsStockset cur_rsStock = ( exec @strSQL)Flapper

View Replies !
Variable Type For Fetcing The Cursor Record In Tsql Cursor
what is the equivalent of the %rowtype in oracle for the tsql

View Replies !
Could Not Complete Cursor Operation Because The Set Options Have Changed Since The Cursor Was Declared.
I'm trying to implement a sp_MSforeachsp howvever when I call sp_MSforeach_worker
I get the following error can you please explain this problem to me so I can over come the issue.
 

Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 31

Could not complete cursor operation because the set options have changed since the cursor was declared.

Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 32

Could not complete cursor operation because the set options have changed since the cursor was declared.

Msg 16917, Level 16, State 1, Procedure sp_MSforeach_worker, Line 153

Cursor is not open.
 
here is the stored procedure:
 

Alter PROCEDURE [dbo].[sp_MSforeachsp]

@command1 nvarchar(2000)

, @replacechar nchar(1) = N'?'

, @command2 nvarchar(2000) = null

, @command3 nvarchar(2000) = null

, @whereand nvarchar(2000) = null

, @precommand nvarchar(2000) = null

, @postcommand nvarchar(2000) = null

AS

/* This procedure belongs in the "master" database so it is acessible to all databases */

/* This proc returns one or more rows for each stored procedure */

/* @precommand and @postcommand may be used to force a single result set via a temp table. */

declare @retval int

if (@precommand is not null) EXECUTE(@precommand)

/* Create the select */

EXECUTE(N'declare hCForEachTable cursor global for

SELECT QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME)

FROM INFORMATION_SCHEMA.ROUTINES

WHERE ROUTINE_TYPE = ''PROCEDURE''

AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(SPECIFIC_SCHEMA)+''.''+QUOTENAME(ROUTINE_NAME)), ''IsMSShipped'') = 0 '

+ @whereand)

select @retval = @@error

if (@retval = 0)

EXECUTE @retval = [dbo].sp_MSforeach_worker @command1, @replacechar, @command2, @command3, 0

if (@retval = 0 and @postcommand is not null)

EXECUTE(@postcommand)

RETURN @retval

 

GO

 
example useage:
 

EXEC sp_MSforeachsp @command1="PRINT '?' GRANT EXECUTE ON ? TO [superuser]"

GO

View Replies !
Join Cursor With Table Outside Of Cursor
part 1

Declare @SQLCMD varchar(5000)
DECLARE @DBNAME VARCHAR (5000)

DECLARE DBCur CURSOR FOR
SELECT U_OB_DB FROM [@OB_TB04_COMPDATA]

OPEN DBCur
FETCH NEXT FROM DBCur INTO @DBNAME


WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @SQLCMD = 'SELECT T0.CARDCODE, T0.U_OB_TID AS TRANSID, T0.DOCNUM AS INV_NO, ' +
+ 'T0.DOCDATE AS INV_DATE, T0.DOCTOTAL AS INV_AMT, T0.U_OB_DONO AS DONO ' +
+ 'FROM ' + @DBNAME + '.dbo.OINV T0 WHERE T0.U_OB_TID IS NOT NULL'
EXEC(@SQLCMD)
PRINT @SQLCMD
FETCH NEXT FROM DBCur INTO @DBNAME

END

CLOSE DBCur
DEALLOCATE DBCur


Part 2

SELECT
T4.U_OB_PCOMP AS PARENTCOMP, T0.CARDCODE, T0.CARDNAME, ISNULL(T0.U_OB_TID,'') AS TRANSID, T0.DOCNUM AS SONO, T0.DOCDATE AS SODATE,
SUM(T1.QUANTITY) AS SOQTY, T0.DOCTOTAL - T0.TOTALEXPNS AS SO_AMT, T3.DOCNUM AS DONO, T3.DOCDATE AS DO_DATE,
SUM(T2.QUANTITY) AS DOQTY, T3.DOCTOTAL - T3.TOTALEXPNS AS DO_AMT
INTO #MAIN
FROM
ORDR T0
JOIN RDR1 T1 ON T0.DOCENTRY = T1.DOCENTRY
LEFT JOIN DLN1 T2 ON T1.DOCENTRY = T2.BASEENTRY AND T1.LINENUM = T2.BASELINE AND T2.BASETYPE = T0.OBJTYPE
LEFT JOIN ODLN T3 ON T2.DOCENTRY = T3.DOCENTRY
LEFT JOIN OCRD T4 ON T0.CARDCODE = T4.CARDCODE
WHERE ISNULL(T0.U_OB_TID,0) <> 0
GROUP BY T4.U_OB_PCOMP, T0.CARDCODE,T0.CARDNAME, T0.U_OB_TID, T0.DOCNUM, T0.DOCDATE, T3.DOCNUM, T3.DOCDATE, T0.DOCTOTAL, T3.DOCTOTAL, T3.TOTALEXPNS, T0.TOTALEXPNS


my question is,
how to join the part 1 n part 2?
is there posibility?

View Replies !
Importing Excel Sheet Which Have Dynamic Column Name And Dynamic Number Of Columns
Hi Craig/Kamal,
 
I got your email address from your web cast. I really enjoyed the web cast and found it to be
very informative.
 
Our company is planning to use SSIS (VS 2005 / SQL Server 2005). I have a quick question
regarding the product. I have looked for the information on the web, but was not able to find
relevant information.
 
We are getting Source data from two of our client in the form of Excel Sheet. These Excel sheets
Are generated using reporting services. On examining the excel sheet, I found out that the name
Of the columns contain data itself, so the names are not static such as Jan 2007 Sales, Feb 2007 Sales etc etc.
And even the number of columns are not static. It depends upon the range of date selected by the user.
 
I wanted to know, if there is a way to import Excel sheet using Integration Services by defining the position
Of column, instead of column name and I am not sure if there is a way for me to import excel with dynamic
Number of columns.
 
Your help in this respect is highly appreciated!
 
Thanks,
 
 
Hi Anthony, I am glad the Web cast was helpful.
 
Kamal and I have both moved on to other teams in MSFT and I am a little rusty in that area, though in general dynamic numbers of columns in any format is always tricky.  I am just assuming its not feasible for you to try and get the source for SSIS a little closer to home, e.g. rather than using Excel output from Reporting Services, use the same/some form of the query/data source that RS is using.
 
I suggest you post a question on the SSIS forum on MSDN and you should get some good answers.
http://forums.microsoft.com/msdn/showforum.aspx?forumid=80&siteid=1
http://forums.microsoft.com/msdn/showforum.aspx?forumid=80&siteid=1
 
Thanks
 

 
Craig Guyer
SQL Server Reporting Services
 

View Replies !
SSRS 2005 - Email Report On Execution To Dynamic List With Dynamic Parameters = No Schedule
Hi,
   I have a need to display on screen AND email a pdf report to email addresses specified at run time, executing the report with a parameter specified by the user. I have looked into data driven subscriptions, but it seems this is based on scheduling. Unfortunately for the majority of the project I will only have access to SQL 2005 Standard Edition (Production system is Enterprise), so I cannot investigate thoroughly.

So, is this possible using data driven subscriptions? Scenario is:

1. User enters parameter used for query, as well as email addresses.
2. Report is generated and displayed on screen.
3. Report is emailed to addresses specified by user.

Any tips on how to get this working?

Thanks

Mark Smith

View Replies !
Merge Replication W/ Dynamic Row Filter - Not 'dynamic' After First Initial Sync?
If anyone could confirm...

SQL Server 2000 SP4 to multiple SQL Server 2005 Mobile Edition on PDAs. My DB on SQL2k is published with a single dynamic row filter using host_name() on my 'parent' table and also join filters from parent to child tables. The row filter uses joins to other tables elsewhere that are not published to evaluate what data is allowed through the filter.

E.g. Published parent table that contains suppliers names, etc. while child table is suppliers' products. The filter queries host_name(s) linked to suppliers in unpublished table elsewhere.

First initial sync with snapshot is correct and as I expected - PDA receives only the data from parent (and thus child tables) that matches the row filter for the host_name provided.

However - in my scenario host_name <--> suppliers may later be updated E.g. more suppliers assigned to a PDA for use or vice versa. But when I merge the mobile DB, the new data is not downloaded? Tried re-running snapshot, etc., no change.

Question: I thought the filters would remain dynamic and be applied on each sync?

I run a 'harmless' update on parent table using TSQL e.g. "update table set 'X' = 'X'" and re-sync. Now the new parent records are downloaded - but the child records are not!

Question: I wonder why if parent records are supplied, why not child records?

If I delete existing DB and sync new, I get the updated snapshot and all is well - until more data added back at server...

Any help would be greatly appreciated. Is it possible (or not) to have dynamic filters run during second or subsequent merge?

View Replies !
Cursor Inside A Cursor
I'm new to cursors, and I'm not sure what's wrong with this code, it run for ever and when I stop it I get cursor open errors




declare Q cursor for
select systudentid from satrans


declare @id int

open Q
fetch next from Q into @id
while @@fetch_status = 0
begin

declare c cursor for

Select
b.ssn,
SaTrans.SyStudentID,
satrans.date,
satrans.type,
SaTrans.SyCampusID,
Amount = Case SaTrans.Type
When 'P' Then SaTrans.Amount * -1
When 'C' Then SaTrans.Amount * -1
Else SaTrans.Amount END

From SaTrans , systudent b where satrans.systudentid = b.systudentid

and satrans.systudentid = @id




declare @arbalance money, @type varchar, @ssn varchar, @amount money, @systudentid int, @transdate datetime, @sycampusid int, @before money

set @arbalance = 0
open c
fetch next from c into @ssn, @systudentid, @transdate, @type, @sycampusid, @amount

while @@fetch_status = 0
begin

set @arbalance = @arbalance + @amount
set @before = @arbalance -@amount

insert c2000_utility1..tempbalhistory1
select @systudentid systudentid, @sycampusid sycampusid, @transdate transdate, @amount amount, @type type, @arbalance Arbalance, @before BeforeBalance
where( convert (int,@amount) <= -50
or @amount * -1 > @before * .02)
and @type = 'P'




fetch next from c into @ssn, @systudentid, @transdate, @type, @sycampusid, @amount
end
close c
deallocate c
fetch next from Q into @id

end
close Q
deallocate Q


select * from c2000_utility1..tempbalhistory1
truncate table c2000_utility1..tempbalhistory1

View Replies !
Mixing Dynamic SQL With Non-Dynamic In Stored Proc
I have a Stored Procedure for processing a Bill of Material.

One column on the Assembly Table is a Function Name that contains some busniess rules.

OK, now I'm doing a Proof of Concept and I'm stumped.

Huuuuh!

I will ultimately have about 100 of these things. My plan was using Dynamic SQL to go execute the function.

Note: The function just returns a bit.

So; here's what I had in mind ...

if isnull(@FnNameYN,'') <> ''
exec spinb_CheckYN @FnNameYN, @InvLineID, @FnBit = @FnBit output




CREATE PROCEDURE dbo.spinb_CheckYN
@FnNameYN varchar(50),
@InvLineID int,
@FnBit bit output
AS

declare @SQL varchar(8000)

set @SQL = '
if dbo.' + @FnNameYN + ' (' + convert(varchar(31),@InvLineID) + ')) = 1
set @FnBit = 1
else
set @FnBit = 0'

exec (@SQL)
GO



Obviously; @FnBit is not defined in @SQL so that execution will not work.
Server: Msg 137, Level 15, State 1, Line 4
Must declare the variable '@FnBit'.
Server: Msg 137, Level 15, State 1, Line 5
Must declare the variable '@FnBit'.


So; is there a way to get a value out of a Dynamic SQL piece of code and get that value INTO my OUTPUT variable?


My many thanks to anyone who can solve this riddle for me.
Thank You!


Sigh: For now, it looks like I'll have a huge string of "IF" statements for each business rule function, as follows:
Hopefully a better solution comes to light.

------ Vertical Build1 - Std Vanes -----------
if @FnNameYN = 'fnb_YN_B1_14'
BEGIN
if dbo.fnb_YN_B1_14 (convert(varchar(31),@InvLineID) ) = 1
set @FnBit = 1
else
set @FnBit = 0
END

------ Vertical Build1 - Scissor Vanes -----------
if @FnNameYN = 'fnb_YN_B1_15'
BEGIN
if dbo.fnb_YN_B1_15 (convert(varchar(31),@InvLineID) ) = 1
set @FnBit = 1
else
set @FnBit = 0
END
.
.
.
etc.

View Replies !
Client Side Cursor Vs Sever Side Cursor?
I having a difficult time here trying to figure out what to do here.I need a way to scroll through a recordset and display the resultswith both forward and backward movement on a web page(PHP usingADO/COM)..I know that if I use a client side cursor all the records get shovedto the client everytime that stored procedure is executed..if thisdatabase grows big wont that be an issue?..I know that I can set up a server side cursor that will only send therecord I need to the front end but..Ive been reading around and a lot of people have been saying never touse a server side cursor because of peformance issues.So i guess im weighing network performance needs with the client sidecursor vs server performance with the server side cursor..I am reallyconfused..which one should I use?-Jim

View Replies !
Dynamic Source And Dynamic Destination
I have a requirment which i have partly accomplished , but could not get through completely
 
i have a file which comes in a standard format ending with date and seq number ,
 
suppose , the file name is abc_yyyymmdd_01 , for first copy , if it is copied more then once the sequence number changes to 02 and 03 and keep going on .
 
then i need to transform those in to new file comma delimited destination file with a name abc_yyyymmdd,txt and others counting file counting record abc_count_yyyymmdd.txt.  and move it to a designated folder. and the source file is then moved to archived folder
 
 
what i have taken apprach is
 
script task select source file --------------------> data flow task------------------------------------------> script task to destination file
 
dataflow task -------------------------> does count and copy in delimited format
 
 
 
what is happening here is  i can accomlish a regular source file convert it to delimited destination file --------> and move it to destination folder with script task .  
 
but cannot  work the dynamic pick of a source file.
 
 
please advise with your comments or solution you have
 
 

View Replies !
Dynamic Columns For Dynamic SQL
I have created a dynamic SQL program that returns a range of columns (1 -12) based on the date range the user may select. Each dynamic column is month based, however, the date range may overlap from one year to another. Thus, the beginning month for one selection may be October 2005, while another may have the beginning month of January 2007.

Basically, the dynamic SQL is a derived Pivot table. The problem that I need to resolve is how do I now use this dynamic result set in a Report. Please keep in mind that the name of the columns change based on the date range select.

I have come to understand that a dynamic anything is a moving target!

 

Please advise.

View Replies !
How Cursor Used In Asp.net
hii have creted cursor but i want to use in my asp.net programming when some insert or delete command is work that time i want to excute my cursor how can i do that using asp.net with c#  waiting for replaythanks 

View Replies !
Is This Possible Without A Cursor?
 I have something like
 update table
set field = ...
where field = ...
 and for each entry that was effected by this query I want to insert an entry into another table.
I have always done this with cursors is there a more effecient way?  For some reason cursors run a lot slower on my sql2005 server than the sql2000 server...

View Replies !
Use Of Cursor
 
 I need some help with the concept of a Cursor, as I see it being used in a stored procedure I need to maintain.
Here is some code from the stored proc. Can someone tell me what is going on here. I haveleft out some of the sql, but have isolated the Cursor stuff.
Open MarketCursor  -- How is MarketCursor loaded with data ?
FETCH NEXT
FROM MarketCursorINTO ItemID, @Item, @Reguest
WHILE @@FETCH_STATUS = 0BEGIN
 
DEALLOCATE MarketCursor
 

View Replies !
Cursor For
Hi,
Declare wh_ctry_id CURSOR FOR 
 
Is "cursor for" is a function or datatype or what is this?
Regards
Abdul

View Replies !
Need Help With A Cursor
I hope this is the appropriate forum for this question, if not then I apologize.
I've got a SQL Server 2000 stored procedure that returns data to be used in a crystal report in Visual Studio 2005.  Most of the stored procedure works well, but there is a point where I need to calculate an average number of days been a group of date pairs. 
I'm not familiar with cursors, but I think that I will need to use one to achieve the result I am looking for so I came up with the code below which is a snippet from my stored procedure.  In this part of the code, the sp looks at the temporary table #lmreport (which holds all of the data that is returned at the end to crystal) and for every row in the table where the terrid is 'T' (the territory is domestic), it selects all of those territories from the territory table and loops through them to determine the date averages (by calling a nested stored procedure, also included below) for each territory and then updates #lmreport with that data.
When I try to run the stored procedure, I get "The column prefix '#lmreport' does not match with a table name or alias name used in the query." on the line indicated. 
Does anyone have any idea what might be wrong or if this will even work the way I need it to?
Thank you in advance.
 

View Replies !
Need Cursor Help
Hello, I'm trying to construct a cursor that will sequentually increment a number and then update a column with the incremented number. My propblem is that all the rows in the table are being updated with the base number +1. So all rows are updated with 278301. BUT, what I really want is for only the items with adrscode of 'bill to' to be given an incremented number.
For example, if there are only five rows of 100 with an adrscode = 'bill to' then only five rows will be updated and the value of the custnmbr should be, 278301, 278302, 278303 .....
I could really use some help with this cursor:
Declare @CustomerName as char (60),     @seqno as int,     @BaseSeqno as intset @Baseseqno = 278300
declare c cursor for select custnmbr from NXOFcustomers Where adrscode = 'BILL TO' order by custnmbropen cfetch next from c into @CustomerNamewhile @@fetch_status=0begin set @seqno = @BaseSeqno + 1
update NXOFcustomers set custnmbr = @seqnoWhere custnmbr = @CustomerName                    fetch next from c into @CustomerNameend close cdeallocate c
 

View Replies !
Cursor And UDf
Hello:
I am trying to define a cursor as follows:
 DECLARE   EmployeeList CURSOR FOR   dbo.GetRecord(@EmployeeID,@CurrentDate)Can't I use a UDF in the CURSOR FOR ?Help please.thank you.

View Replies !
Is Cursor Best Way To Go?
I need to get two values from a complex SQL statement which returns a singlerecord and use those two values to update a single record in a table. Inorder to assign those two values to variables and then use those variablesin the UPDATE statement, I created a cursor and used Fetch Next.... Into.This way, I only have to call the complex SQL once instead of twice.This seems like the best way to go. However, I've always used cursors forscrolling through resultsets. In this case, though, there is just a singlerecord being returned, and the cursor doesn't scroll.Is that the most efficient way to go, or is there a better way to be able touse both values from the SQL statement without having to call it twice?Thanks.

View Replies !
To Use A Cursor Or To Not Use A Cursor
I need to loop through a set of records to build a string. I can dothis without using a cursor by inserting the records into a temporarytable with an identity column. Count the number of records in thetemporary table and loop though the table selecting the values andbuilding the string where the identity column = the loop number.Is this more or less efficient than just using a cursor? If so why isit more or less efficient?Please explain in detailThank You,Jim Lewis

View Replies !
Cursor Help PLEASE!
Yes, I know that cursors are gauche, but I can't see a solution usingqueries and I'm pretty adept at them. This will be running once a dayin the wee small hours when minimal server activity will be takingplace, it will be handling 700-1000ish records. The box is a P4/SQL2000 with lots of ram and multiple CPUs.The code for creating and populating the table in question follows thecursor code.The application is for medical transport billing. We take people tothe doctor and home again and the health plan pays us. A one-waytrip, home -> doctor, is a single ‘line item'. A round trip, home ->doctor -> home is rolled up, the charge summed, and billed as a singleline item. A three-leg, home -> doctor -> pharmacy -> home, is billedas three line items.This code is just for identifying the data, once this works correctlyI'll add the code in for doing the rollup and I'm confident I canhandle that.If I ruled the world, every leg of every trip would be a single lineitem and I wouldn't have to deal with this rollup BS, but I don't makethe policy, I just have to code it. <g>A trip is a round trip if the date, account number, and passenger nameis the same and the origin street of record X equals the destinationstreet of record X+1. The problem is that X+1 could be the start of around trip and X+2 could be the completing leg of a round trip. Soyou could have a scenario of hospital -> home -> doctor -> home inwhich X is one-way and X+1 & X+2 form a round trip.BLERG! Any help is greatly appreciated, it has me stumped./*select trip_id, acct_number, passenger, street, dest_street,flat_rate, screated, smeteroff, remark1, remark2from zvoucherstodbf order by cast(screated as smalldatetime),acct_number, passenger, smeteroff*/declare @roundtrip integerdeclare @cmsg char(200)declare @Trip_ID char(11)declare @acct_number char(11)declare @passenger char(12)declare @created char(22)declare @meter_off char(22)declare @street char(32)declare @dest_street char(32)declare @remark1 char(32)declare @remark2 char(32)declare @flat_rate smallintdeclare @prev_cmsg char(200)declare @prev_Trip_ID char(11)declare @prev_acct_number char(11)declare @prev_passenger char(12)declare @prev_created char(22)declare @prev_meter_off char(22)declare @prev_street char(32)declare @prev_dest_street char(32)declare @prev_remark1 char(32)declare @prev_remark2 char(32)declare @prev_flat_rate smallintdeclare cVoucher cursor scroll forselect trip_id, acct_number, passenger, street, dest_street, screated,smeteroff, remark1, remark2, flat_ratefrom zVouchersToDBF--where screated = '12/03/03'order by screated, acct_number, passenger, smeteroffopen cVoucher--Load the @Prev_ (previous record) variables with the first recordfetch from cVoucher into @prev_trip_id, @prev_acct_number,@prev_passenger,@prev_street, @prev_dest_street, @prev_created, @prev_meter_off,@prev_remark1, @prev_remark2, @prev_flat_rate--Initialize current variablesselect @trip_id = @prev_trip_idselect @acct_number = @prev_acct_numberselect @passenger = @prev_passengerselect @street = @prev_streetselect @dest_street = @prev_dest_streetselect @created = @prev_createdselect @meter_off = @prev_meter_offselect @remark1 = @prev_remark1select @remark2 = @prev_remark2while @@fetch_status = 0--not EOFbeginselect @roundtrip = 0if (@prev_created = @created) and (@prev_acct_number = @acct_number)and (@prev_passenger = @passenger)and (@prev_street =@dest_street)-- MATCH! Apparent round tripbeginselect @roundtrip = 1select @prev_trip_id = @trip_idselect @prev_acct_number = @acct_numberselect @prev_passenger = @passengerselect @prev_street = @streetselect @prev_dest_street = @dest_streetselect @prev_created = @createdselect @prev_meter_off = @meter_offselect @prev_remark1 = @remark1select @prev_remark2 = @remark2endif (@roundtrip = 0)beginfetch next from cVoucher into @trip_id, @acct_number, @passenger,@street, @dest_street, @created, @meter_off, @remark1, @remark2,@flat_rateif (@prev_created = @created) and (@prev_acct_number = @acct_number)and (@prev_passenger = @passenger)and (@prev_street =@dest_street)-- MATCH! Apparent round tripselect @roundtrip = 1else--definitely one-way tripselect @roundtrip = 0fetch prior from cVoucher into @trip_id, @acct_number, @passenger,@street, @dest_street, @created, @meter_off, @remark1, @remark2,@flat_rateendif (@roundtrip = 1)beginselect @cMsg = 'Start: ' + rtrim(@prev_created) + ' ' +rtrim(@prev_trip_id) + ': ' + @prev_acct_number + ' ' +rtrim(@prev_meter_off) + ' ' + @prev_passenger + ' ' +rtrim(@prev_street) + ' to ' + @prev_dest_street + ' ' + @prev_remark1+ ' ' + @prev_remark2print @cMsgselect @cMsg = 'End: ' + rtrim(@created) + ' ' + rtrim(@trip_id) +': ' + @acct_number + ' ' + rtrim(@meter_off) + ' ' + @passenger + ' '+ rtrim(@street) + ' to ' + @dest_street + ' ' + @remark1 + ' ' +@remark2print @cMsgprint ''endelsebeginselect @cMsg = 'One-Way: ' + rtrim(@created) + ' ' + rtrim(@trip_id)+ ': ' + @acct_number + ' ' + rtrim(@meter_off) + ' ' + @passenger + '' + rtrim(@street) + ' to ' + @dest_street + ' ' + @remark1 + ' ' +@remark2print @cMsgprint ''endselect @prev_trip_id = @trip_idselect @prev_acct_number = @acct_numberselect @prev_passenger = @passengerselect @prev_street = @streetselect @prev_dest_street = @dest_streetselect @prev_created = @createdselect @prev_meter_off = @meter_offselect @prev_remark1 = @remark1select @prev_remark2 = @remark2fetch next from cVoucher into @trip_id, @acct_number, @passenger,@street, @dest_street, @created, @meter_off, @remark1, @remark2,@flat_rateendclose cVoucher--/*--This code works for displaying the data set as a whole-- so you can visually identify what constitutes a round trip.open cVoucherfetch from cVoucher into @trip_id, @acct_number, @passenger,@street, @dest_street, @created, @meter_off, @remark1, @remark2,@flat_ratewhile @@fetch_status = 0beginselect @cMsg = rtrim(@created) + ' ' + rtrim(@trip_id) + ': ' +@acct_number + ' ' + @passenger + ' ' + @street + ' ' + @dest_street +' ' + @meter_off + ' ' + @remark1 + ' ' + @remark2print @cMsgfetch next from cVoucher into @trip_id, @acct_number, @passenger,@street, @dest_street, @created, @meter_off, @remark1, @remark2,@flat_rateendclose cVoucher--*/deallocate cVoucherCREATE TABLE [zVouchersToDBF] ([house] [char] (5) NULL ,[street] [char] (32) NULL ,[district] [char] (8) NULL ,[passenger] [char] (12) NULL ,[remark1] [char] (32) NULL ,[remark2] [char] (32) NULL ,[dest_house] [char] (5) NULL ,[dest_street] [char] (32) NULL ,[dest_district] [char] (13) NULL ,[acct_number] [char] (11) NULL ,[sub_acct_number] [char] (15) NULL ,[flat_rate] [money] NULL ,[car] [char] (3) NULL ,[driver_id] [char] (9) NULL ,[meter_on] [char] (5) NULL ,[meter_off] [char] (5) NULL ,[fare] [char] (9) NULL ,[cancelled] [char] (21) NULL ,[no_trip] [char] (7) NULL ,[no_trip_reason] [int] NULL ,[auth_number] [char] (32) NULL ,[auth_name] [char] (32) NULL ,[trip_id] [char] (7) NULL ,[created] [char] (8) NULL ,[patient_birthday] [char] (16) NULL ,[waittime] [char] (3) NULL ,[sNoTrip] [char] (22) NULL ,[sMeterOn] [char] (22) NULL ,[sMeterOff] [char] (22) NULL ,[sCancelled] [char] (22) NULL ,[sCreated] [char] (22) NULL ,[sPatientBirthday] [char] (22) NULL ,[SystemRate] [money] NULL) ON [PRIMARY]GOInsert zvoucherstodbfValues (null,'100 E 1st',null,'A','X','Y',null,'200 W2nd',null,'1000',null,5.00,null,null,null,'13:20', '5',null,null,null,null,null,'1',null,null,null,nu ll,null,'13:20',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'200 W 2nd',null,'A','X','Y',null,'100 E1st',null,'1000',null,5.00,null,null,null,'14:20', '5',null,null,null,null,null,'2',null,null,null,nu ll,null,'14:20',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'101 E 101',null,'B','X','Y',null,'202 W202',null,'2000',null,10.00,null,null,null,'13:50' ,'10',null,null,null,null,null,'3',null,null,null, null,null,'13:50',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'123 N 456',null,'C','X','Y',null,'234 S321',null,'2000',null,5.00,null,null,null,'13:51', '5',null,null,null,null,null,'4',null,null,null,nu ll,null,'13:51',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'999 N 666',null,'D','X','Y',null,'666 S999',null,'1000',null,7.50,null,null,null,'14:00', '7.5',null,null,null,null,null,'5',null,null,null, null,null,'14:00',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'666 S 999',null,'D','X','Y',null,'999 N666',null,'1000',null,8.00,null,null,null,'14:30', '8',null,null,null,null,null,'6',null,null,null,nu ll,null,'14:30',null,'12/8/2003',null,null)Insert zvoucherstodbfValues (null,'123 n 456',null,'E','X','Y',null,'456 s789',null,'3000',null,5.00,null,null,null,'14:30', '5',null,null,null,null,null,'7',null,null,null,nu ll,null,'14:30',null,'12/8/2003',null,null)

View Replies !
What Is A Cursor?
I had a friend write a stored procedure to perform a function for oneof my clients. What he wrote doesn't fully do what I need, and I hopeto finish it myself. I have programming sense, but not so much withSQL.I'm trying to figure out the code, and he has used something called a"cursor." I'm not sure whether this is an SQL construct or a structurethat he has just labeled "cursor." My guess is that it is an SQLconstruct. Can anyone give me a quick run down of how this works?sincerely,Tyler H.-----------------------------------------------<a href="http://www.seearoomhawaii.com/bed-breakfasts/">bed &breakfasts in Hawaii</a>

View Replies !
It Is Possible With Cursor?
I need to fill a cursor with 3 columns.
A want to use a Select sprocs (for re-use de code), but this sproc return 15 columns and the 3 a need was not the 3 frist. :confused:

Do I need to map the 15 columns with 15 variables locally? Or they have a way easier?


Thanks

View Replies !
Can I Use SQL Instead Of Cursor?
Hi,

I'm currently converting a VB function to SQL-Server. The function uses a cursor to find the "terms of delivery" (TOD) with the highest priority.

I have a table with articlenumber, tod (and lots of other columns that doesn't matter now)

ABC123 , AFG
ABC123 , AFG
ABC123 , BGH
ABC123 , BGH
ABC123 , CDD

"CDD" has the highest priority and therefore ALL with the same articlenumber should use that tod.

The existing function uses a cursor and loops through a recordset and updates every row with the same articlenumber as the current row with the tod with the highest priority (of the ones read) with the same articlenumber.

One update per row takes "forever" to run...

I figured it would be possible to select the tod with the highest priority for one articlenumber into a temp table and then do ONE update to set the tod on all rows...

View Replies !
Can't Use Cursor With SP
Hi

I have a SP and in it I call another SP which returns one row in one column, I need to concatenate the value (varchar) to the query in the first SP.
I tried to use cursor with FAST_FORWARD to fetch the result and concatenate it, but I get an error, here is what I tried:

DECLARE Cur CURSOR FAST_FORWARD
FOR SP_Something @SomeValue

So is it possible to use cursor on SP ? And if it's possible so how ???

Thanks,

Inon.

View Replies !
Get Value From CURSOR
I'm writing a stored procedure that involves looping through a recordset and using the values from the recordset as parameters for a second stored procedure. Here's what I've got so far...

My question is, how do I get the value out of the Cursor? There's only one field.

Declare @Day as int
Declare @Plant as varchar(30)

SET NOCOUNT ON

CREATE Table #Temp (Facility varchar(30), ProductCategory nvarchar(3), Target int, Quantity int, Percentage decimal(10,2), Production_Date smalldatetime,As_Of_Time smalldatetime)

Declare Facility_Cursor CURSOR
For Select Distinct(Facility) From ProductionHistory
OPEN Facility_CURSOR
Declare @Facility_Cursor as sysname

FETCH NEXT From Facility_CURSOR into @Facility_Cursor

WHILE @@FETCHSTATUS = 1

--YESTERDAY
Set @Day = -2

Insert Into #Temp
exec sp_GetDailyProductionByPlantAndCategory @Day, @Facility, 'NAP'

--TODAY
SET @Day = -1
Insert Into #Temp
exec sp_GetDailyProductionByPlantAndCategory @Day, @Facility, 'NAP'

FETCH NEXT FROM Facility_CURSOR into @Facility_Cursor

CLOSE Facility_Cursor
DEALLOCATE Facility_CURSOR

SET NOCOUNT OFF

Select * From #Temp ORDER BY Production_Date, Facility, ProductCategory DESC

View Replies !
How To Do This Without Using A Cursor?
I am in the last stages of designing a forecasting "engine" for my company,
and I'm stuck on something that seems simple in comparison to everything
else I've done so far.

I have product ABC, and it's total sales forecast is 15 units.
I split the forecast into 2 different locations, based on an established percentage. In this case, I'll say 67% in location 'OH', and 33% in location 'AL' That's 10 units 'OH' and 5 units 'AL'. Then I get my actual orders by location, and compare them to the forecast.

If the orders exceed the forecast, I'll use orders, otherwise, I use forecast. Whenever I do that, I need to reduce the forecast for the other location, in order to keep the total forecast of 15 whole. (It is not possible for total orders to exceed total forecast, I've already dealt with that.)


CREATE PROCEDURE tempSelect
AS

CREATE TABLE #tmpTest (
parent char(2),
proj_ship real,
open_ord real,
)

insert into #tmpTest (parent, proj_ship, open_ord)
select 'OH', 10, 4

insert into #tmpTest (parent, proj_ship, open_ord)
select 'AL', 5, 7

SELECT PARENT, 'UNITS' = ???
FROM #TMPTEST

DROP TABLE #TMPTEST
GO


I need help with '???' in the query.

The result set I am looking for is:
OH 8
AL 7

View Replies !
Trying To NOT Use A Cursor...
I need to write a sproc to supply records for a report. The boss has asked
"Of all the tons on order right now, how much is already in inventory, and how much needs to be produced." And "Apply the same logic to just the orders that came in yesterday." It would have been easy, if he hadn't asked for the second part, because now I have to look at each product on each order, rather than comparing total orders for a product to total available inventory.

Here's some sample data for what I need to do:


CREATE TABLE ORDER_ITEM (
ORDER_NUM VARCHAR(10),
SHIP_DATE SMALLDATETIME,
PRODUCT VARCHAR(10),
ORD_TONS REAL)

INSERT INTO ORDER_ITEM (ORDER_NUM, SHIP_DATE, PRODUCT, ORD_TONS)
SELECT '001', '3/1/2006', 'ABC', 4 UNION ALL
SELECT '002', '3/4/2006', 'ABC', 2 UNION ALL
SELECT '002', '3/4/2006', 'DEF', 6 UNION ALL
SELECT '003', '3/7/2006', 'DEF', 8

CREATE TABLE PROD_INVENTORY (
PRODUCT VARCHAR(10),
INV_TONS REAL)

INSERT INTO PROD_INVENTORY (PRODUCT, INV_TONS)
SELECT 'ABC', 5 UNION ALL
SELECT 'DEF', 13



The final recordset needs to be something like:

PRODUCT ORDER_NUM ORD_TONS SFI SFP END_INV
ABC 001 4 4 0 1
ABC 002 2 1 1 0
DEF 002 6 6 0 7
DEF 003 8 7 1 0


SFI = Sales from Inventory
SFP = Sales from production

I need a little help in how to do a running inventory balance (END_INV)
for each item. Once I have that, then I can calculate SFI and SFP.
I could figure out how to do it with a cursor, but it
would probably be pretty slow. I'll have about 10,000 records to sort thru,
and of course there will be more columns than what I show here.

Any ideas would be appreciated.

View Replies !
Cursor
hey all,
i am relatively new to cursors and have created a SP that uses a cursor to populate a table. here is the code

CREATE PROCEDURE sppa_invvoid
(
@invnoint
)

AS

DECLARE @glTranKey int
DECLARE @AcctRefKey int
DECLARE @BatchKey int
DECLARE @CreateDate datetime
DECLARE @CreateType smallint
DECLARE @CurrExchRate float
DECLARE @CurrID varchar (3)
DECLARE @ExtCmnt varchar (255)
DECLARE @FiscPer smallint
DECLARE @FiscYear varchar (5)
DECLARE @GLAcctKey int
DECLARE @JrnlKey int
DECLARE @JrnlNo int
DECLARE @PostAmt decimal(15, 3)
DECLARE @PostAmtHC decimal(15, 3)
DECLARE @PostCmnt varchar (50)
DECLARE @PostDate datetime
DECLARE @PostQty decimal(16, 8)
DECLARE @SourceModuleNo smallint
DECLARE @TranDate datetime
DECLARE @TranKey int
DECLARE @TranNo varchar (10)
DECLARE @TranType int
DECLARE @Companyid varchar(3)
DECLARE @Batchtype int
DECLARE @Userid varchar (30)
DECLARE @Moduleno int
DECLARE @NextBatchNo int
DECLARE @_oRetVal int
DECLARE @iTableNamevarchar(50)
DECLARE @iCommitFlag int
DECLARE @NextJrnlNo int


Set @CompanyID= 'EMA'
Set @JrnlNo = 139
Set @iCommitFlag = 1
Set @JrnlKey = 193
Set @iTableName='tgltransaction'
Set @batchtype = 501
Set @moduleNo = 5
Set @Userid = 'Admin'



EXECUTE spGetNextBatchNo @CompanyID, @BatchType, @UserId, @ModuleNo, @BatchKey OUTPUT, @NextBatchNo OUTPUT, @_oRetVal OUTPUT

Execute spglGiveNextJrnlNo @CompanyID, @JrnlKey, @iCommitFlag, @JrnlNo, @NextJrnlNo OUTPUT




DECLARE cursor_tran CURSOR FOR

select glTranKey, AcctRefKey,CreateDate,CreateType,CurrExchRate,Curr ID,ExtCmnt,FiscPer,FiscYear,GLAcctKey,JrnlKey,Jrnl No,PostAmt,PostAmtHC,PostCmnt,PostDate,PostQty,Sou rceModuleNo,TranDate,TranKey,TranNo,TranType
from tgltransaction where tranno = @invno

OPEN cursor_tran

FETCH NEXT FROM cursor_tran INTO

@glTranKey,
@AcctRefKey,
@CreateDate,
@CreateType,
@CurrExchRate,
@CurrID,
@ExtCmnt,
@FiscPer,
@FiscYear,
@GLAcctKey,
@JrnlKey,
@JrnlNo,
@PostAmt,
@PostAmtHC,
@PostCmnt,
@PostDate,
@PostQty,
@SourceModuleNo,
@TranDate,
@TranKey,
@TranNo,
@TranType





WHILE (@@FETCH_STATUS <> -1)

BEGIN

Execute spgetnextSurrogateKey @iTablename , @glTranKey OUTPUT
/*Execute aaaa*/





INSERT INTO tgltransaction
(glTranKey,
AcctRefKey,
BatchKey,
CreateDate,
CreateType,
CurrExchRate,
CurrID,
ExtCmnt,
FiscPer,
FiscYear,
GLAcctKey,
JrnlKey,
JrnlNo,
PostAmt,
PostAmtHC,
PostCmnt,
PostDate,
PostQty,
SourceModuleNo,
TranDate,
TranKey,
TranNo,
TranType)

Values

(@glTrankey,
@AcctRefKey,
@BatchKey,
@CreateDate,
@CreateType,
@CurrExchRate,
@CurrID,
@ExtCmnt,
@FiscPer,
@FiscYear,
@GLAcctKey,
@JrnlKey,
@JrnlNo,
@PostAmt,
@PostAmtHC,
@PostCmnt,
@PostDate,
@PostQty,
@SourceModuleNo,
@TranDate,
@TranKey,
@TranNo,
@TranType)




FETCH NEXT FROM cursor_tran INTO

@glTranKey,
@AcctRefKey,
@CreateDate,
@CreateType,
@CurrExchRate,
@CurrID,
@ExtCmnt,
@FiscPer,
@FiscYear,
@GLAcctKey,
@JrnlKey,
@JrnlNo,
@PostAmt,
@PostAmtHC,
@PostCmnt,
@PostDate,
@PostQty,
@SourceModuleNo,
@TranDate,
@TranKey,
@TranNo,
@TranType



END
CLOSE cursor_tran
DEALLOCATE cursor_tran
GO


the issue that i am having is after i do the insert, the cursor picks up on the inserted row and it ultimately becomes an infinate loop. what can i do to prevent it from picking up the newly inserted rows. thanks alot

tibor

View Replies !
SQL Cursor?
Hi all,

I have two tables with

IMPORT_TABLE (Imported from MS Excel) <-- Source table
Name
Address
City
State
Zip

CONTACT_TABLE: <-- Target Table
Full_Name
Address_Line1
City
State
Zip


I have to match the name from the Import table with the full_name in Contact table, if it matches, i have to update address / city / state / zip information in the Contact table if and only if corresponding columns in the target table (Contact table) is empty. If the name does not match, i have to insert a new record in contact table.

Should i use SQL cursor? If so could any one provide me with a sample solution?

Thanks in Advance,
Newbie

---------------------------------------------
SQL 2000 on Windows 2000 Server

View Replies !
Using Cursor
Using SQL2005. I need to create a cursor to update a field in a table with current date by Invoice Number. I get an endless loop and record is not updated. Where did I go wrong. David

DECLARE

@GRGR_ID CHAR(10),
@SBSB_ID CHAR(10),
@INVOICE_DUE_DATE DATETIME,
@INVOICE_TOTAL_AMOUNT_DUE MONEY,
@INVOICE_NUMBER CHAR(12),
@PASS1_GENERATION_DATE DATETIME,
@PASS1_TOTAL_AMOUNT_DUE MONEY,
@PASS1_END_OF_GRACE DATETIME



DECLARE DEQ CURSOR FOR
SELECT
GRGR_ID,
SBSB_ID,
INVOICE_DUE_DATE,
INVOICE_TOTAL_AMOUNT_DUE,
INVOICE_NUMBER,
PASS1_GENERATION_DATE,
PASS1_TOTAL_AMOUNT_DUE,
PASS1_END_OF_GRACE

FROM dbo.RPT_DELINQUENCY_TEST WHERE INVOICE_NUMBER = '080710019183'

OPEN DEQ

FETCH DEQ INTO
@GRGR_ID,
@SBSB_ID,
@INVOICE_DUE_DATE,
@INVOICE_TOTAL_AMOUNT_DUE,
@INVOICE_NUMBER,
@PASS1_GENERATION_DATE,
@PASS1_TOTAL_AMOUNT_DUE,
@PASS1_END_OF_GRACE

WHILE @@FETCH_STATUS = 0
BEGIN

UPDATE dbo.RPT_DELINQUENCY_TEST SET @PASS1_GENERATION_DATE = GETDATE()
WHERE SBSB_ID=@SBSB_ID AND GRGR_ID=@GRGR_ID AND INVOICE_NUMBER=@INVOICE_NUMBER

END

CLOSE DEQ
DEALLOCATE DEQ

Thank for your help.

View Replies !
Msg 512 On Cursor
Everytime I execute this procedure it gives a msg 512 subquery returns more then one value. Can someone just explain why or what I'm doing wrong? Thanks in advance

Here is my code:

create procedure insert_sku_info
AS
Declare
@method varchar(40),
@sku int,
@location varchar(40)

Declare insert_cur Cursor For
select a.method, s.sku, s.location
from archive_sku a INNER JOIN sku s on a.sku = s.sku
and a.location = s.location

Open insert_cur

Fetch Next from insert_cur
Into @method, @sku, @location

While (@@Fetch_Status = 0)
Begin

print @method + @sku + @location

Update sku
set method = @method
where sku = @sku
and location = @location

Fetch Next from insert_cur
Into @method, @sku, @location

End
close insert_cur
deallocate insert_cur

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved