Showing posts with label row. Show all posts
Showing posts with label row. Show all posts

Thursday, March 29, 2012

cursor vs. select

buddies,
situation: a processing must take place on every row of a table, and
output results to another table, that can't be done via an insert
into..select query (let's assume that it's not possible for now).
There're 2 solutions I have in mind:
1) open a cursor and cycle through each row (The table can have up to
1M rows)
2) create a clustered index (i.e on an identity column) then have a
loop like:
declare @.i int, @.rows int,
@.col1 varchar(20), @.col2 varchar(20),... @.coln varchar(20),
@.outval1 varchar(20),... -- output values
select @.i=1, @.rows = max(xid) from tblname -- xid is clustered indexed
while (@.i<=@.rows)
begin
select @.col1 = col1, @.col2 = col2,...@.coln = coln
from tblname
where xid = i
-- do the processing on the variables
-- then insert results to another table
set @.i = @.i+1
end
I'd like to know your ideas of which one would be more efficient. Any
other solutions are much appreciated
thanks,
TamyYou obviously skipped the essential question: "Is there a better way
than processing the data a row at a time?". 99.99% of the time the
answer is YES.

On those other occassions, it may depend on what you are doing with the
data but there probably isn't much to choose between the two
approaches. Lots of times a cursor IS the best way to process
row-by-row. For 1 million rows, though, I doubt it's even worth
considering doing it row-by-row. What makes you think that's the only
way?

> Any other solutions are much appreciated

For that we'll need a better spec so that we can write the INSERT
statement:
http://www.aspfaq.com/etiquette.asp?id=5006

--
David Portas
SQL Server MVP
--|||>> processing must take place on every row of a table, and output
results to another table, that can't be done via an insert into..select
query (let's assume that it's not possible for now). <<

That is a **huge** leap of faith and goes against **decades** of SQL
programming experience. It also goes against some proofs in computer
science that a declarative language has the computational power of a
procedural language.

But assuming that the goal is to slow down and hurt the company as much
as possible while mis-using SQL, the cursor will be faster than the
proprietary, non-relational procedural approach. Look at the number of
passes over the base tables and time wasted on indexing.

On the other hand, if you would like to actually post the problem to
get a solution which will run order of magnitude faster instead of
asking for kludges, then you can be better helped here. I feel I like
I just got an email asking for help committing suicide.|||Haha,
chill out guys, I'm on your side. The thing is I don't have access to
the code that runs on every row (decrypting it is another story - I'd
be fired then). The no. 2) runs in 30' for 1M rows - it seems I gotta
be cool with it.|||On 8 Apr 2005 08:58:49 -0700, vuht2000 wrote:

>Haha,
>chill out guys, I'm on your side. The thing is I don't have access to
>the code that runs on every row (decrypting it is another story - I'd
>be fired then). The no. 2) runs in 30' for 1M rows - it seems I gotta
>be cool with it.

Hi Tamy,

I guess that being stuck with a stored proc that works only row-based
and that you can't legally change or replace counts as a valid reason
for using cursor-based logic.

Your solution #2 has one flaw: it assumes that all identity values will
be a contiguous range. That can't be guaranteed, though - there might be
gaps. You'll have to adapt the code to handle those.

I expect that using a cursor will be faster - IF you use the correct
settings (FAST_FORWARD comes to mind), make sure that tempdb is on a
fast disk, and have your source table properly indexed. But the only way
to know for sure which method is the fastest is to test them both, in
your environment and with your data. Comment the call to the stored proc
and the insert statement to test just the speed of then row-by-row
processing.

Best, Hugo
--

(Remove _NO_ and _SPAM_ to get my e-mail address)

cursor usage

hi guys

i have a table that contains a tremendous amount of row. i have written a stored procedure that takes a summary of that information and updates it's master table as well as another table. the problem is it takes very long to do. is what i am doing correct or is there a better way. here is the source

CREATE PROCEDURE update_cvrbatches
AS

declare @.code varchar(25),@.type varchar(3),@.batchno varchar(10),@.batchqty Float,@.issued float,@.returned float,@.transfered float,@.itemcount float,@.totestcost float,@.totactcost float,@.reserved float,@.warehouse varchar(3)

Update cvrwarehouse set BoughtQty =0, IssuedQty = 0, ReservedQty =0 ,Returned = 0 ,Transfered = 0

DECLARE getbatches CURSOR
for
select Code,Type,BatchNo,sum(BoughtQty) as BoughtQty,sum(IssuedQty) as IssuedQty,sum(ReservedQty) as ReservedQty,sum(ReturnedQty) as ReturnedQty,sum(TransferQty) as TransferQty,count(Barcode) as ItemCount,
sum(EstCost) as EstCost,sum(ActCost) as ActCost,Warehouse
from cvrbatches
Group by Code,Type,Colour,Quality,CustomField,BatchNo,Warehouse
OPEN getbatches

FETCH NEXT FROM getbatches into @.code,@.type ,@.batchno ,@.batchqty,@.issued ,@.reserved,@.returned ,@.transfered ,@.itemcount ,@.totestcost ,@.totactcost ,@.warehouse
WHILE @.@.FETCH_STATUS = 0
BEGIN
--doen iets hier

update cvrbatchctrl set BatchQty = @.batchqty, Issued = @.issued, Reserved = @.reserved ,Returned = @.returned ,Transfered = @.transfered, ItemCount = @.itemcount,TotalEstCost = @.totestcost,TotalActCost = @.totactcost
where Code = @.code and Type = @.type and Warehouse = @.warehouse and BatchNo = @.batchno
update cvrwarehouse set BoughtQty =BoughtQty + @.batchqty, IssuedQty = IssuedQty + @.issued, ReservedQty = ReservedQty + @.reserved ,Returned = Returned + @.returned ,Transfered = Transfered + @.transfered
where Code = @.code and Type = @.type and Warehouse = @.warehouse

FETCH NEXT FROM getbatches into @.code,@.type ,@.batchno ,@.batchqty,@.issued ,@.reserved,@.returned ,@.transfered ,@.itemcount ,@.totestcost ,@.totactcost,@.warehouse

END
CLOSE getbatches
DEALLOCATE getbatches

is there a better way?

Hi,

better use setbased solutions rather than cursors, one example would be (*untested*) the below one: (put in a more human readble format)


update cvrbatchctrl
set BatchQty = SUbQuery.BoughtQty,
Issued = SUbQuery.IssuedQty,
Reserved = SUbQuery.ReservedQty,
Returned = SUbQuery.ReservedQty,
Transfered = SUbQuery.TransferQty,
ItemCount = SUbQuery.ItemCount,
TotalEstCost = SUbQuery.EstCost,
TotalActCost = SUbQuery.ActCost
FROM cvrbatchctrl cvr
INNER JOIN
(
select Code,
Type,
BatchNo,
Warehouse,
sum(BoughtQty) as BoughtQty,
sum(IssuedQty) as IssuedQty,
sum(ReservedQty) as ReservedQty,
sum(ReturnedQty) as ReturnedQty,
sum(TransferQty) as TransferQty,
count(Barcode) as ItemCount,
sum(EstCost) as EstCost,
sum(ActCost) as ActCost
from cvrbatches
Group by Code,Type,Colour,Quality,CustomField,BatchNo,Warehouse
) SUbQuery
ON
cvr.Code = SUbQuery.Code and
cvr.Type = SUbQuery.Type and
cvr.Warehouse = SUbQuery.Warehouse and
cvr.BatchNo = SUbQuery.batchno


--Second one, taking the value from the first update (make surethat your condition is complete in the below script)

update cvrwarehouse
set BoughtQty = cvrhouse.BoughtQty + @.batchqty,
IssuedQty = cvrhouse.IssuedQty + @.issued,
ReservedQty = cvrhouse.ReservedQty + @.reserved ,
Returned = cvrhouse.Returned + @.returned ,
Transfered = cvrhouse.Transfered + @.transfered
FROM cvrwarehouse cvrhouse
INNER JOIN cvrbatchctrl cvrbatch
ON
cvrhouse.Code = cvrbatchctrl.Code AND
cvrhouse.Type = cvrbatchctrl.Type
cvrhouse.Warehouse = cvrbatchctrl.Warehouse

HTH, jens Suessmeyer.

http://www.sqlserver2005.de

|||

Thank you.

haven't tried it yet but it sure makes for an interesting solution.

let you know as soon as i do.

again thanks

|||

i just tested it

works really well and the speed is a lot better

thanks again

Cursor Tuning Help!

This cursor is processing one row per second, all it is doing is appending a value to a column. There are 847,000 rows and I can't leave the query to run for 10 days! help!

CREATE procedure [dbo].sp_USR_TEMP_SESSIONAL_ATTENDANCE_APPEND
as

begin

DECLARE @.I_UPN varchar(13)
DECLARE @.I_SURNAME varchar(50)
DECLARE @.I_FORENAME varchar(50)
DECLARE @.I_DOB datetime
DECLARE @.I_GENDER varchar(1)
DECLARE @.I_LEA varchar(3)
DECLARE @.I_DFES varchar(4)
DECLARE @.I_ATTEND_YEAR varchar(4)
DECLARE @.I_WEEK_BEGINNING datetime
DECLARE @.I_ATTEND_CODES varchar(14)

declare @.cnt int

set nocount on

declare cur CURSOR

for select upn,
surname,
forename,
dob,
gender,
'353' as lea,
dfes,
attend_year,
week_beginning,
attend_codes
from tmpATTEND_IMPORT

for read only

open cur

fetch from cur into
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,
@.I_ATTEND_CODES

truncate table tmpATTEND_IMPORT_APPENDED

while @.@.fetch_status = 0
begin
set @.cnt = (select count(*) as cnt from tmpATTEND_IMPORT_APPENDED
where upn = @.I_UPN
and surname = @.I_SURNAME
and forename = @.I_FORENAME
and dob = @.I_DOB
and gender = @.I_GENDER
and lea = @.I_LEA
and dfes = @.I_DFES
and attend_year = @.I_ATTEND_YEAR)

if @.cnt = 0 insert tmpATTEND_IMPORT_APPENDED(
upn,
surname,
forename,
dob,
gender,
lea,
dfes,
attend_year,
week_beginning,
attend_codes)
values (
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,
@.I_ATTEND_CODES)

else update tmpATTEND_IMPORT_APPENDED
set attend_codes = attend_codes+@.I_ATTEND_CODES
where upn = @.I_UPN and
surname = @.I_SURNAME and
forename = @.I_FORENAME and
dob = @.I_DOB and
gender = @.I_GENDER and
lea = @.I_LEA and
dfes = @.I_DFES and
attend_year = @.I_ATTEND_YEAR

fetch next from cur into
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,
@.I_ATTEND_CODES

end

close cur

deallocate cur

end
GO

I tried adapting a post resolved on Romanian SQL Server User Group (www.sqlserver.ro) , to concatenate the columns

DECLARE @.MyTable TABLE (ID INT PRIMARY KEY, VAL VARCHAR(64))

INSERT INTO @.MyTable VALUES (1, 'Cristian')

INSERT INTO @.MyTable VALUES (2, 'Sorin')

INSERT INTO @.MyTable VALUES (3, 'Narcis')

DECLARE @.Lista VARCHAR(MAX)

SET @.Lista = '';

SELECT @.Lista=@.Lista + VAL + ' ' FROM @.MyTable

SELECT RTRIM(@.Lista) AS Lista

GO

-- Output

Lista

Cristian Sorin Narcis

so try the following procedure :

CREATE procedure [dbo].sp_USR_TEMP_SESSIONAL_ATTENDANCE_APPEND
as

begin

DECLARE @.I_UPN varchar(13)
DECLARE @.I_SURNAME varchar(50)
DECLARE @.I_FORENAME varchar(50)
DECLARE @.I_DOB datetime
DECLARE @.I_GENDER varchar(1)
DECLARE @.I_LEA varchar(3)
DECLARE @.I_DFES varchar(4)
DECLARE @.I_ATTEND_YEAR varchar(4)
DECLARE @.I_WEEK_BEGINNING datetime
DECLARE @.I_ATTEND_CODES varchar(14)


set nocount on

declare cur CURSOR

//select only distinct rows

for select upn,
surname,
forename,
dob,
gender,
'353' as lea,
dfes,
attend_year,
week_beginning,
from tmpATTEND_IMPORT
group by upn,surname,forename,dob,gender,lea,dfes,attend_year

for read only

open cur

fetch from cur into
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,


truncate table tmpATTEND_IMPORT_APPENDED

while @.@.fetch_status = 0
begin
//adding to @.I_ATTEND_CODES only rows that respect where clause
select @.I_ATTEND_CODES=attend_codes+@.I_ATTEND_CODES
from tmpATTEND_IMPORT
where upn = @.I_UPN and
surname = @.I_SURNAME and
forename = @.I_FORENAME and
dob = @.I_DOB and
gender = @.I_GENDER and
lea = @.I_LEA and
dfes = @.I_DFES and
attend_year = @.I_ATTEND_YEAR

// and insert what it find and add

insert tmpATTEND_IMPORT_APPENDED(
upn,
surname,
forename,
dob,
gender,
lea,
dfes,
attend_year,
week_beginning,
attend_codes)
values (
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,
@.I_ATTEND_CODES)

fetch next from cur into
@.I_UPN,
@.I_SURNAME,
@.I_FORENAME,
@.I_DOB,
@.I_GENDER,
@.I_LEA,
@.I_DFES,
@.I_ATTEND_YEAR,
@.I_WEEK_BEGINNING,


end

close cur

Tuesday, March 27, 2012

cursor or while loop?

hello,
i have 160,000 rows in a table. need to send out an email to somebody
for each row.
currently using a cursor to loop through the rows and calling COM email
component to send the emails
ran low on resources after about 100,000 records
would it be better to do something like this?
DECLARE @.Rowcount int
SELECT @.RowCount=COUNT(*) from table
WHILE @.RowCount > 0
BEGIN
SELECT TOP 1 @.somevar=somevar FROM table
SET @.RowCount = @.@.ROWCOUNT
IF @.Rowcount > 0
BEGIN
send the email
delete the record
END
END
this would only grab one record at a time. any recommendations?
TIA
NeilPass the result set to the front end and do not try to do this in the
database.|||Check out http://www.sqldev.net there is a xp_smtp_sendmail which you can
use to send your mail.
You will need to use a cursor still because there isn't anything that takes
a set.
I'd create a temporary table or table variable of the rows you want to email
first, then send the emails and join back removing the rows; you might want
recoverability in which case use a permenent table or something similar -
you don't want to lose the position if the server goes down.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
<neilmcguigan@.gmail.com> wrote in message
news:1131321608.259481.84490@.g49g2000cwa.googlegroups.com...
> hello,
> i have 160,000 rows in a table. need to send out an email to somebody
> for each row.
> currently using a cursor to loop through the rows and calling COM email
> component to send the emails
> ran low on resources after about 100,000 records
> would it be better to do something like this?
> DECLARE @.Rowcount int
> SELECT @.RowCount=COUNT(*) from table
> WHILE @.RowCount > 0
> BEGIN
> SELECT TOP 1 @.somevar=somevar FROM table
> SET @.RowCount = @.@.ROWCOUNT
> IF @.Rowcount > 0
> BEGIN
> send the email
> delete the record
> END
> END
> this would only grab one record at a time. any recommendations?
> TIA
> Neil
>|||That just won't scale.
The number of round trips 160,000 would be even slower.
This is one of many examples where keeping it inside the SQL Server engine
scales better and is more maintable (you don't have to code using two
different langauges and worry about a front end app).
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1131322861.083235.253060@.g43g2000cwa.googlegroups.com...
> Pass the result set to the front end and do not try to do this in the
> database.
>|||I really had a lot of reliability problems with sql server mail.
I just don't trust mapi based mail anymore.
xp_smtp_sendmail is dead reliable. I pump huge amounts through it everyday.
What are we going to do with Yukon?
Tony, do you know if xp's written for 2000 will work with 2005 or is the
native mail OK in 2005?
Paul
"Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
news:ekRlvE34FHA.2548@.TK2MSFTNGP10.phx.gbl...
> Check out http://www.sqldev.net there is a xp_smtp_sendmail which you can
> use to send your mail.
> You will need to use a cursor still because there isn't anything that
> takes a set.
> I'd create a temporary table or table variable of the rows you want to
> email first, then send the emails and join back removing the rows; you
> might want recoverability in which case use a permenent table or something
> similar - you don't want to lose the position if the server goes down.
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> <neilmcguigan@.gmail.com> wrote in message
> news:1131321608.259481.84490@.g49g2000cwa.googlegroups.com...
>|||Hi Paul,
Believe me - they got the message with MAPI mail!
Its been rewritten (again), but this time properly - MAPI is only there for
backward compatibility, there is a new SMTP mail built into SQL Server 2005
and its highly scalable too (at last!).
I will be glad to see the back of Outlook 2000 and SQL Server.
Tony.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"Paul Cahill" <xyzpaul.xyzcahill@.dsl.pipex.com> wrote in message
news:OEEASy34FHA.1140@.tk2msftngp13.phx.gbl...
>I really had a lot of reliability problems with sql server mail.
> I just don't trust mapi based mail anymore.
> xp_smtp_sendmail is dead reliable. I pump huge amounts through it
> everyday.
> What are we going to do with Yukon?
> Tony, do you know if xp's written for 2000 will work with 2005 or is the
> native mail OK in 2005?
> Paul
>
> "Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
> news:ekRlvE34FHA.2548@.TK2MSFTNGP10.phx.gbl...
>|||Additional...
You've really got to get your head round what the SQL Server product is now,
its not just a RDBMS its a whole host of things that we can take advantage
of when building applications, be they simple or complex.
You don't have to go off to DB2 etc... in order to build a dimensional
model, you can use Analysis Services which is part of the SQL Server product
set and has been since 2000.
You don't have to go off and buy another text search package, you can use
Full-Text indexing which is built into the product as well.
Please (oh please), bring your knowledge up-to-date; you are so far behind
its embarrasing.
Tony Rogerson
SQL Server MVP
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1131322861.083235.253060@.g43g2000cwa.googlegroups.com...
> Pass the result set to the front end and do not try to do this in the
> database.
>|||I'm going to have to kindof disagree with you on this one. Making a
round-trip on each result would be a horrendous solution; however,
returing a full batch 160,000 records to the client wouldn't be bad at
all (even if the client were the SQL Server machine.). I consider my
databases to be dynamic entities whose purpose is efficient storage,
retrieval and manipulation of data. I wouldn't dream of calling a COM
component from SQL Server; even the idea of embedding .NET assemblies
in 2005 scares me a bit.
The two solutions I would consider using would be embedded an ActiveX
script in a SQL Server Agent job step. I prefer Python, however,
VBScript and JScript are readily available for use. Or you can easily
throw together a quick .NET console app.
EXAMPLE (Compile using: csc /t:exe SendEMails.cs):
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mail;
class SendEmails
{
static void Main(string[] args)
{
SqlDataAdapter da = new SqlDataAdapter(@."
SELECT EmailAddress
FROM TableName
", "server=.;database=MyDatabase;integrated security=sspi;");
DataTable dt = new DataTable();
da.Fill(dt);
SmtpMail.SmtpServer =
"smtp.domain.com";
foreach (DataRow dr in dt.Rows)
SmtpMail.Send("from@.domain.com", dr["EmailAddress"].ToString(),
"Subject", "MessageText");
}
}
-Alan|||Thanks Tony that's good news.
Now I've only got to remember how those DTS tasks I wrote last year work :)
Paul
"Tony Rogerson" <tonyrogerson@.sqlserverfaq.com> wrote in message
news:O8r7xG44FHA.2888@.tk2msftngp13.phx.gbl...
> Hi Paul,
> Believe me - they got the message with MAPI mail!
> Its been rewritten (again), but this time properly - MAPI is only there
> for backward compatibility, there is a new SMTP mail built into SQL Server
> 2005 and its highly scalable too (at last!).
> I will be glad to see the back of Outlook 2000 and SQL Server.
> Tony.
> --
> Tony Rogerson
> SQL Server MVP
> http://sqlserverfaq.com - free video tutorials
>
> "Paul Cahill" <xyzpaul.xyzcahill@.dsl.pipex.com> wrote in message
> news:OEEASy34FHA.1140@.tk2msftngp13.phx.gbl...
>|||thanks for all the info guys.
i need something that can run continuously, reliably, minimal resouce
use
thinking i might go to an external program, write a .net service
perhaps.
maybe grab a couple hundred records at a time, process them, update.
i liked the all sql model as it didn't seem to use too many resources.
but i like the error handing in .net better.

Thursday, March 22, 2012

Cursor and row retrieval question

Hi everyone, I have a cursor that goes through one table and does a
comparison with another table, code below
==============
CREATE PROCEDURE spMyDataBaseMatch AS
set nocount on
Declare @.FirstName varchar(100)
Declare @.LastName varchar(100)
Declare @.PhoneNumber varchar(100)
Declare @.CourseCode varchar(50)
Declare myCursor Cursor FOR
select FirstName, LastName, PhoneNumber from person
Open myCursor
Fetch Next From myCursor INTO @.FirstName, @.LastName, @.PhoneNumber
While @.@.fetch_status = 0
BEGIN
Select PERLEGALFIRSTNAMETEXT, PERLEGALSURNAMETEXT, OTEINTERNALIDCODE from
MyDataBase6.dbo.vwEnquiriesAllStudents WHERE PERLEGALFIRSTNAMETEXT =
@.FirstName AND PERLEGALSURNAMETEXT = @.LastName
if @.@.ROWCOUNT > 0
BEGIN
----------------
-- I have a question about this next piece
----------------
SELECT @.CourseCode = OTEINTERNALIDCODE FROM
MyDataBase6.dbo.vwEnquiriesAllStudents WHERE PERLEGALFIRSTNAMETEXT =
@.FirstName AND PERLEGALSURNAMETEXT = @.LastName
----------------
-- End question
----------------

insert into MyDataBaseMatch VALUES (@.FirstName + ' ' +
@.LastName,@.CourseCode )
END
Fetch Next From myCursor INTO @.FirstName, @.LastName, @.PhoneNumber
END
deallocate myCursor
GO
=================

Is it possible for me to associate an attribute value in a Select statement?
Like the following

Select @.CourseCode = OTEINTERNALIDCODE, PERLEGALFIRSTNAMETEXT,
PERLEGALSURNAMETEXT, from MyDataBase6.dbo.vwEnquiriesAllStudents WHERE
PERLEGALFIRSTNAMETEXT = @.FirstName AND PERLEGALSURNAMETEXT = @.LastName

instead of what I have written between the tags?
----------------
--
----------------

Thanks in advance
MarkAlways avoid cursors where you can. It looks like your proc can be
re-written as a single INSERT statement that will perform far more
efficiently:

CREATE PROCEDURE spMyDataBaseMatch AS

SET NOCOUNT ON

INSERT INTO MyDataBaseMatch
SELECT firstname + ' ' + lastname, S.oteinternalidcode
FROM Person AS P
JOIN vwEnquiriesAllStudents AS S
ON P.firstname = S.perlegalfirstnametext
AND P.lastname = S.perlegalsurnametext

GO

In answer to the question I think you are asking, variables can be assigned
in a SELECT statement but only if the SELECT doesn't otherwise need to
return any rows to the client. For example, this is valid syntax:

SELECT @.CourseCode = oteinternalidcode,
@.firstname = perlegalfirstnametext,
@.lastname = perlegalsurnametext
FROM vwEnquiriesAllStudents
WHERE ...

but this is not:

SELECT @.CourseCode = oteinternalidcode,
perlegalfirstnametext, perlegalsurnametext
FROM vwEnquiriesAllStudents
WHERE ...

Hope this helps.

--
David Portas
SQL Server MVP
--

cursor and fetch statement

can you please give me an example of using the FETCH and cursor statement

And make to be able to fetch more that one row at a time,

lets say the two database are TEST(fetch to) and TLC (fetch from) and both have Table called Mine with same fieldsSally,

I have moved your post into the forum from the MSSQL articles

MODERATOR|||

Quote:

Originally Posted by Sally1053

can you please give me an example of using the FETCH and cursor statement

And make to be able to fetch more that one row at a time,

lets say the two database are TEST(fetch to) and TLC (fetch from) and both have Table called Mine with same fields


would you mind giving a more detailed specs? maybe FETCH is not the right solutionsql

Wednesday, March 21, 2012

Current Row Number

Hi,
Is there a way to get the current Row number.
If get this as a result of select statement,
12 as
56 yu
89 gh
I need like this
1 12 as
2 56 yu
3 89 gh
I saw some eg.s using temporary tables. But Is there a straight forward way
to get this.
Thanks
KiranYou can use Group By, Order By clauses to get the row number. or you can
also make sure of subquery to get the row number..check examples here
http://www.aspfaq.com/show.asp?id=2427
instead of temp tables, you can make use of table variables in the example
provided in the above link.
Av.
http://dotnetjunkies.com/WebLog/avnrao
http://www28.brinkster.com/avdotnet
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>|||Kiran wrote:
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight
> forward way to get this.
> Thanks
> Kiran
This uses a temp table as well, but maybe it's something different than
what you saw. Can you tell us how you are going to to know the order of
the rows during the select? Do you have an ORDER BY for the statement
that is driving the final order of the rows?
create table #OrderTest(col1 int not null, col2 varchar(3) not null)
insert into #OrderTest (col1, col2) values (10, 'AA')
insert into #OrderTest (col1, col2) values (12, 'AA')
insert into #OrderTest (col1, col2) values (13, 'AA')
insert into #OrderTest (col1, col2) values (16, 'AA')
Select IDENTITY(int, 1, 1) as "OrderCol", col1, col2
INTO #OrderTest2
From #OrderTest
Select * from #OrderTest2
Drop Table #OrderTest
Drop Table #OrderTest2
David Gugick
Imceda Software
www.imceda.com|||Hi Kiran,
Wait for SQL 2005
Regards,
Daniel
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>

Current Row Number

Hi,
Is there a way to get the current Row number.
If get this as a result of select statement,
12 as
56 yu
89 gh
I need like this
1 12 as
2 56 yu
3 89 gh
I saw some eg.s using temporary tables. But Is there a straight forward way
to get this.
Thanks
KiranYou can use Group By, Order By clauses to get the row number. or you can
also make sure of subquery to get the row number..check examples here
http://www.aspfaq.com/show.asp?id=2427
instead of temp tables, you can make use of table variables in the example
provided in the above link.
--
Av.
http://dotnetjunkies.com/WebLog/avnrao
http://www28.brinkster.com/avdotnet
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>|||Kiran wrote:
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight
> forward way to get this.
> Thanks
> Kiran
This uses a temp table as well, but maybe it's something different than
what you saw. Can you tell us how you are going to to know the order of
the rows during the select? Do you have an ORDER BY for the statement
that is driving the final order of the rows?
create table #OrderTest(col1 int not null, col2 varchar(3) not null)
insert into #OrderTest (col1, col2) values (10, 'AA')
insert into #OrderTest (col1, col2) values (12, 'AA')
insert into #OrderTest (col1, col2) values (13, 'AA')
insert into #OrderTest (col1, col2) values (16, 'AA')
Select IDENTITY(int, 1, 1) as "OrderCol", col1, col2
INTO #OrderTest2
From #OrderTest
Select * from #OrderTest2
Drop Table #OrderTest
Drop Table #OrderTest2
David Gugick
Imceda Software
www.imceda.com|||Hi Kiran,
Wait for SQL 2005
Regards,
Daniel
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>sql

Current Row Number

Hi,
Is there a way to get the current Row number.
If get this as a result of select statement,
12 as
56 yu
89 gh
I need like this
1 12 as
2 56 yu
3 89 gh
I saw some eg.s using temporary tables. But Is there a straight forward way
to get this.
Thanks
Kiran
You can use Group By, Order By clauses to get the row number. or you can
also make sure of subquery to get the row number..check examples here
http://www.aspfaq.com/show.asp?id=2427
instead of temp tables, you can make use of table variables in the example
provided in the above link.
Av.
http://dotnetjunkies.com/WebLog/avnrao
http://www28.brinkster.com/avdotnet
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>
|||Kiran wrote:
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight
> forward way to get this.
> Thanks
> Kiran
This uses a temp table as well, but maybe it's something different than
what you saw. Can you tell us how you are going to to know the order of
the rows during the select? Do you have an ORDER BY for the statement
that is driving the final order of the rows?
create table #OrderTest(col1 int not null, col2 varchar(3) not null)
insert into #OrderTest (col1, col2) values (10, 'AA')
insert into #OrderTest (col1, col2) values (12, 'AA')
insert into #OrderTest (col1, col2) values (13, 'AA')
insert into #OrderTest (col1, col2) values (16, 'AA')
Select IDENTITY(int, 1, 1) as "OrderCol", col1, col2
INTO #OrderTest2
From #OrderTest
Select * from #OrderTest2
Drop Table #OrderTest
Drop Table #OrderTest2
David Gugick
Imceda Software
www.imceda.com
|||Hi Kiran,
Wait for SQL 2005
Regards,
Daniel
"Kiran" <Kiran@.nospam.net> wrote in message
news:#0zmneS$EHA.2112@.TK2MSFTNGP14.phx.gbl...
> Hi,
> Is there a way to get the current Row number.
> If get this as a result of select statement,
> 12 as
> 56 yu
> 89 gh
> I need like this
> 1 12 as
> 2 56 yu
> 3 89 gh
> I saw some eg.s using temporary tables. But Is there a straight forward
way
> to get this.
> Thanks
> Kiran
>

current row no?

i know there is a function to count number of rows in a group, but is there anyway of numbering each row?

So that I can use =Last(ReportIems("norow") to find the last row on the page?

Thanks

Try putting this into your detail row (where GroupName is the name of your group):

=RowNumber("GroupName")

Hope this helps.

Jarret

|||Thank you SO much.... I used this to a Page no for each group ;)

current row no?

i know there is a function to count number of rows in a group, but is there anyway of numbering each row?

So that I can use =Last(ReportIems("norow") to find the last row on the page?

Thanks

Try putting this into your detail row (where GroupName is the name of your group):

=RowNumber("GroupName")

Hope this helps.

Jarret

|||Thank you SO much.... I used this to a Page no for each group ;)

Sunday, March 11, 2012

Cumulative total in matrix

Hi,
For columns in a matrix, I need to add the row value to the row value in
previous column. Is there a way to do this?
Here is what I want the matrix results to look like:
year1 year2 year3 year4
Amount 1 3 4 7
Total 1 4 8 15
Year is the column group value and amount is the row group value. Total is
the field I am looking for how to calculate.
Thanks!Initially I thought you were after a running total, but looking at your
example that doesn't appear to be the case.
You will have to do this in the underlying query by including the two
consecutive year's values on the same row; i.e.
Select A.Year, Sum(A.Value), (Select Sum(B.Value) From MyTable B Where
B.Year = A.Year-1)
From MyTable A
Group By A.Year
(I'm not sure this is syntactically correct, but you get my drift)
Having said that, mathematically what you're showing would appear
incorrect, effectively the year2 total is included in the year4 total
twice. What are you trying to show?
Chris
Me wrote:
> Hi,
> For columns in a matrix, I need to add the row value to the row value
> in previous column. Is there a way to do this?
> Here is what I want the matrix results to look like:
> year1 year2 year3 year4
> Amount 1 3 4 7
> Total 1 4 8 15
> Year is the column group value and amount is the row group value.
> Total is the field I am looking for how to calculate.
> Thanks!|||Hi Chris,
Thanks for replying.
What I wrote is a little unclear but my example is correct. They want to
add the current year to the running total of the previous years. Does that
make sense?
Thanks,
Melissa
"Chris McGuigan" wrote:
> Initially I thought you were after a running total, but looking at your
> example that doesn't appear to be the case.
> You will have to do this in the underlying query by including the two
> consecutive year's values on the same row; i.e.
> Select A.Year, Sum(A.Value), (Select Sum(B.Value) From MyTable B Where
> B.Year = A.Year-1)
> From MyTable A
> Group By A.Year
> (I'm not sure this is syntactically correct, but you get my drift)
> Having said that, mathematically what you're showing would appear
> incorrect, effectively the year2 total is included in the year4 total
> twice. What are you trying to show?
> Chris
>
> Me wrote:
> > Hi,
> >
> > For columns in a matrix, I need to add the row value to the row value
> > in previous column. Is there a way to do this?
> >
> > Here is what I want the matrix results to look like:
> >
> > year1 year2 year3 year4
> > Amount 1 3 4 7
> > Total 1 4 8 15
> >
> > Year is the column group value and amount is the row group value.
> > Total is the field I am looking for how to calculate.
> >
> > Thanks!
>|||Melissa, Yes that makes sense (logically not statistically), but I
think you may have mis-interpreted it.
In the example you have given, year 3 is neither a running total nor a
grand total. It is year1 + year2 + year1 + year3, that's the effect of
what you are doing.
So they want the current year added to each past year? I still can't
see a reason for that, but hey! the customers always right!
You are better off doing this in the query. Matrix controls like fairly
simply structured data, so hide the complexity in the query, on the
lines of my original post.
The more I look at this, the more I think you probably just need a
running total. If that is the case use =RunningValue( ... ) in the cell.
Chris
Me wrote:
> Hi Chris,
> Thanks for replying.
> What I wrote is a little unclear but my example is correct. They
> want to add the current year to the running total of the previous
> years. Does that make sense?
> Thanks,
> Melissa
>
> "Chris McGuigan" wrote:
> > Initially I thought you were after a running total, but looking at
> > your example that doesn't appear to be the case.
> >
> > You will have to do this in the underlying query by including the
> > two consecutive year's values on the same row; i.e.
> > Select A.Year, Sum(A.Value), (Select Sum(B.Value) From MyTable B
> > Where B.Year = A.Year-1)
> > From MyTable A
> > Group By A.Year
> > (I'm not sure this is syntactically correct, but you get my drift)
> >
> > Having said that, mathematically what you're showing would appear
> > incorrect, effectively the year2 total is included in the year4
> > total twice. What are you trying to show?
> >
> > Chris
> >
> >
> >
> > Me wrote:
> >
> > > Hi,
> > >
> > > For columns in a matrix, I need to add the row value to the row
> > > value in previous column. Is there a way to do this?
> > >
> > > Here is what I want the matrix results to look like:
> > >
> > > year1 year2 year3 year4
> > > Amount 1 3 4 7
> > > Total 1 4 8 15
> > >
> > > Year is the column group value and amount is the row group value.
> > > Total is the field I am looking for how to calculate.
> > >
> > > Thanks!
> >
> >

Sunday, February 19, 2012

CTE to replace cursor

I am trying to replace a cursor with a CTE. Is it possible to scroll
through the records returned using the CTE?
i.e.
If I get more than one row returned check the values in each row? A bit
like a result set?
I know there is some recursive stuff you can do but I don't think it
will work for this as it is not a Parent/Child i.e. hierarchy
situation.
Thanks for any help offered
JamieYou'll need to post more details of your problem.
If you are interested in recursive CTEs, there is an excellent article
here
http://www.sqlservercentral.com/col...lserver2005.asp|||>I am trying to replace a cursor with a CTE. Is it possible to scroll
> through the records returned using the CTE?
Can you explain exactly what you are trying to accomplish? This description
is a bit vague. http://www.aspfaq.com/5006

> If I get more than one row returned check the values in each row? A bit
> like a result set?
Depending on exactly what you are doing "in each row," a cursor may be the
only way. Again, if you can explain better exactly what you are doing, with
real specs, we may be able to provide more helpful input.
http://www.aspfaq.com/5006|||Thanks for your responses.
The following is what I am attempting.
If I have:
select 1 AS Counter, custid, code from customer where custid IN (8072,
7786)
which returns:
CUSTID CODE
7786 [code]
8072 #
I turn this into a CTE
WITH CustCte(CustID, Code)
AS
(SELECT CustID, Code FROM dbo.Customer WHERE CustID IN (8072, 7786))
SELECT CustID, Code FROM CustCte
GO
Which naturally gives me:
CUSTID CODE
7786 [code]
8072 #
I now want navigate through each row i.e.
For first row if Code = XYZ then do something. else move to next row
If next row Code = XYX then do something.
I came up with the following and various different variations but can't
get the Counter to increment.
WITH CustCte(Counter, CustID, Code)
AS
(SELECT 1 AS Counter, CustID, Code FROM dbo.Customer WHERE CustID IN
(8072, 7786))
SELECT Counter = Counter + 1, CustID, Code FROM CustCte
do you have further thoughts.|||jamie.downs@.risk.sungard.com wrote:
> Thanks for your responses.
> The following is what I am attempting.
> If I have:
> select 1 AS Counter, custid, code from customer where custid IN (8072,
> 7786)
> which returns:
> CUSTID CODE
> 7786 [code]
> 8072 #
> I turn this into a CTE
> WITH CustCte(CustID, Code)
> AS
> (SELECT CustID, Code FROM dbo.Customer WHERE CustID IN (8072, 7786))
> SELECT CustID, Code FROM CustCte
> GO
> Which naturally gives me:
> CUSTID CODE
> 7786 [code]
> 8072 #
> I now want navigate through each row i.e.
> For first row if Code = XYZ then do something. else move to next row
> If next row Code = XYX then do something.
>
This is not a full description of the problem. What we need to know is
what is the operation that you are calling "do something". If "do
something" means "do some data manipulation" then chances are you can
do it without a cursor or a loop.
The best way to specify your problem is to post DDL, sample data and
show your required end results.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||If the "do something" part can be written as a function you don't need a
cursor. Even if "do something" returns a set - CROSS APPLY can be used.
The Counter in your CTE would only increment in a recursion - i.e. if there
was a recursive member in addition to the anchor member. And even then the
value would reflect the number of recursions, not the number of rows.
An alternative to cursors may be a table variable, but this would require
you to add the logic to "simulate" a cursor.
ML
http://milambda.blogspot.com/|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.
A CTE is like a VIEW, and not anything like a cursor. There is no
scrolling in SQL since it is a declarative language.|||>> I now want navigate through each row.. <<
"Navigate" is a dirty word in RDBMS. In fact, we replaced navigational
DBMS systems with RDBMS to get rid of it.
Since I cannot figure out the "do something" function from what you
posted, my guess would be that you want a CASE expression. something
like this:
UPDATE Customers
SET foobar
= CASE WHEN foo_code = 'xyz'
THEN 42 ELSE foobar END
WHERE cust_id IN (8072, 7786);
But who knows?|||> CREATE TABLE #Cust2 (CustID INT, Code VARCHAR(10))
INSERT #Cust2 SELECT CustID, CASE Code
WHEN 'Cust1' THEN NULL ELSE Code END
FROM #Cust;
SELECT * FROM #Cust2;
-- poof! Cursor be gone
Or better yet, eliminate the need for #Cust2 in the first place:
SELECT CustID, CASE Code
WHEN 'Cust1' THEN NULL ELSE Code END
FROM #Cust;
If we had seen how #Cust was populated in the first place, we can probably
improve the performance even further by eliminating that I/O. But again,
you haven't provided enough details. The line count of your stored
procedure hardly tells us what it is actually doing. In general, stop
trying to do Visual Basic style programming in the database...|||Hi Aaron,
Thanks for your reply. I did say it was a much simplified version of
the original proc. I find it quite amusing that the general comments
you hear about TSQL is to avoid Cursors and Temp tables wherever
possible and to make SQL objects as simple as possible which what I am
trying to achieve. Not VB. You still want more details. Well her is
the full blown proc. No I did not write it.
CREATE procedure DBO.Prc_Get_Checks
@.CURSORSQL VARCHAR(8000),
@.WHERECLAUSE TEXT,
@.CHECKSFORDEALVIOLATIONS BIT,
@.CALCULATEMANUAL BIT,
@.SHOWINACTIVE BIT = 0
AS
BEGIN
SET NOCOUNT ON
DECLARE @.CheckID INT
DECLARE @.PortfolioID INT
DECLARE @.ClassID INT
DECLARE @.MeasureID INT
DECLARE @.ChecksType INT
DECLARE @.Value1 VARCHAR(200)
DECLARE @.Value2 VARCHAR(800)
DECLARE @.Message VARCHAR(200)
DECLARE @.MessageID INT
DECLARE @.Severity INT
DECLARE @.ReviewDate DATETIME
DECLARE @.ExpiryDate DATETIME
DECLARE @.AssetID INT
DECLARE @.TemplateRef INT
DECLARE @.IsConditional BIT
DECLARE @.Active BIT
DECLARE @.Threshold FLOAT
DECLARE @.HasTransfers BIT
DECLARE @.CheckSymbol VARCHAR(20)
DECLARE @.ChecksTypeSymbol VARCHAR(20)
-- template variables
DECLARE @.TemplateMeasureID INT
DECLARE @.TemplateChecksType INT
DECLARE @.TemplateValue1 VARCHAR(200)
DECLARE @.TemplateValue2 VARCHAR(800)
DECLARE @.TemplateMessage VARCHAR(200)
DECLARE @.TemplateMessageID INT
DECLARE @.TemplateSeverity INT
DECLARE @.TemplateReviewDate DATETIME
DECLARE @.TemplateExpiryDate DATETIME
DECLARE @.TemplateAssetID INT
DECLARE @.TemplateActive BIT
DECLARE @.TemplateThreshold FLOAT
DECLARE @.TemplateChecksTypeSymbol VARCHAR(20)
DECLARE @.TemplatePortfSymbol VARCHAR(20)
DECLARE @.Ctrl_Amt_Class_Symbol VARCHAR(20)
DECLARE @.Ctrl_Amt FLOAT
DECLARE @.Ctrl_Active BIT
DECLARE @.Duplicate_CheckCount INT
DECLARE @.CHECKSTAB TABLE
(CheckID INT,
PortfolioID INT,
ClassID INT,
MeasureID INT,
ChecksType INT,
Value1 VARCHAR(200),
Value2 VARCHAR(800),
Message VARCHAR(200),
MessageID INT,
Severity INT,
ReviewDate DATETIME,
ExpiryDate DATETIME,
AssetID INT,
TemplateRef INT,
IsConditional BIT,
Active BIT,
Threshold FLOAT,
HasTransfers BIT)
-- Declare a cursor that represents placeholder/ordinary check rows
from the checks table
-- for portfolios specified in this function's parameter
-- concatenate the two...
EXEC(@.CURSORSQL + @.WHERECLAUSE)
OPEN CHECK_CURSOR
-- Fetch the cursor column values into variables.
-- These some of these variables' values may be overridden for
placeholders
FETCH NEXT FROM CHECK_CURSOR INTO
@.CheckID,
@.PortfolioID,
@.ClassID,
@.MeasureID,
@.ChecksType,
@.Value1,
@.Value2,
@.Message,
@.MessageID,
@.Severity,
@.ReviewDate,
@.ExpiryDate,
@.AssetID,
@.TemplateRef,
@.IsConditional,
@.Active,
@.Threshold,
@.HasTransfers,
@.CheckSymbol,
@.ChecksTypeSymbol
WHILE @.@.FETCH_STATUS = 0
BEGIN
-- IF @.CHECKSYMBOL = 'CHECK_LIMIT_AUTO' OR (@.CHECKSYMBOL =
'CHECK_LIMIT_MANUAL' AND @.CALCULATEMANUAL = 1)
-- then we have a placeholder template, so override some of the
values
-- If we have a placeholder template with a Template Reference,
override some of the values
-- NB: It's now possible to have placeholders without template
references stored in the DB, in which case the template
-- is determined at runtime by the CRS Server software. This is
part of CHG109212, June 2004.
IF ((@.ChecksTypeSymbol = 'CHECKS_AUTO') AND (@.TemplateRef IS
NOT NULL))
BEGIN
-- Get the placeholder's template column values using the
template ref checkID
SELECT
@.TemplateMeasureID = Checks.MeasureID,
@.TemplateChecksType = Checks.ChecksType,
@.TemplateValue1 = Checks.Value1,
@.TemplateValue2 = Checks.Value2,
@.TemplateMessage = Checks.Message,
@.TemplateMessageID = Checks.MessageID,
@.TemplateSeverity = Checks.Severity,
@.TemplateReviewDate = Checks.ReviewDate,
@.TemplateExpiryDate = Checks.ExpiryDate,
@.TemplateAssetID = Checks.AssetID,
@.TemplateActive = Checks.Active,
@.TemplateThreshold = Checks.Threshold,
@.TemplatePortfSymbol = DefnPortfolio.Symbol,
@.TemplateChecksTypeSymbol = C2.Symbol
FROM
Checks,Portfolio, DefnPortfolio, Class C2
WHERE Checks.CheckID = @.TemplateRef
AND Checks.PortfolioID = Portfolio.PortfolioID
AND DefnPortfolio.PfolDefnID = Portfolio.ClassID
AND C2.ClassID = Checks.ChecksType
-- Override placeholder's MESSAGE, SEVERITY, VALUE1,
VALUE2, REVIEWDATE, EXPIRYDATE, MEASUREID, and MESSAGEID values with
those
-- of its template
SET @.MeasureID = @.TemplateMeasureID
SET @.Value1 = @.TemplateValue1
SET @.Value2 = @.TemplateValue2
SET @.Message = @.TemplateMessage
SET @.MessageID = @.TemplateMessageID
SET @.Severity = @.TemplateSeverity
SET @.ReviewDate = @.TemplateReviewDate
SET @.ExpiryDate = @.TemplateExpiryDate
-- If the Template Limit is 'unlimited' then set the
CheckType in the returned (placeholder) row to 'unlimited' as well
IF (@.TemplateChecksTypeSymbol = 'CHECKS_UNLIMITED')
BEGIN
SET @.ChecksType = @.TemplateChecksType
END
-- Find out which control amount class (customer,parent or
ultimate) the template uses (e.g. match PFOL_CUSTOMER)
SELECT @.Ctrl_Amt_Class_Symbol =
dbo. GET_CTRL_AMT_SYMBOL(@.TemplatePortfSymbol
)
-- override the VALUE of the placeholder using the template
(and in certain cases the control amt)
-- " " ASSETID of the placeholder using either the
template's ASSETID (or in certain cases the ASSETID of the control
amount)
-- " " ACTIVE column of the placeholder so that if the
template is inactive the placeholder is also INACTIVE (or in certain
cases the ACTIVE column
IF @.Ctrl_Amt_Class_Symbol IS NULL --then there isn't a
control amount, so return the template value as actual values (i.e.
non-perecentages)
BEGIN
-- ...then return the template's value column as the
result
SET @.Value1 = @.TemplateValue1
SET @.Value2 = @.TemplateValue2
SET @.AssetID = @.TemplateAssetID
IF @.TemplateActive = 0 SET @.Active=0
END
ELSE
-- VALUE is the template's percentages * control
currency,
-- ASSETID is that of the control currency
-- ACTIVE is only true if the control currency,
template and placeholder are all active
BEGIN
-- first get information from the CustControlAmounts
table
SELECT @.Ctrl_Amt=Ctrl.Amount,
@.AssetID=Ctrl.AssetID,@.Ctrl_Active=Ctrl.Active
FROM dbo.CustControlAmounts Ctrl, dbo.Portfolio
PlaceholderPortf, dbo.Checks C, dbo.Class CL
WHERE --join conditions for getting the control
amount from CUSTCONTROLAMOUNTS.
--a row in CUSTCONTROLAMOUNTS is
idenitifed with a HOSTID,CUSTID and CLASSID
Ctrl.HostID = PlaceholderPortf.HostID
AND Ctrl.CustID = PlaceholderPortf.CustID
AND Ctrl.TypeID = CL.ClassID
AND CL.Symbol = @.Ctrl_Amt_Class_Symbol
AND PlaceholderPortf.PortfolioID =
C.PortfolioID
AND C.CheckID = @.CheckID
-- fix for BUG111446: if there is no control amount,
use values from the template
IF (@.AssetID IS NULL) OR (@.Ctrl_Amt IS NULL) OR
(@.Ctrl_Active IS NULL)
BEGIN
SET @.Value1 = @.TemplateValue1
SET @.Value2 = @.TemplateValue2
SET @.AssetID = @.TemplateAssetID
IF @.TemplateActive = 0 SET @.Active=0
END
ELSE
BEGIN
-- we do have a control amount, so act on it
accordingly
IF (@.Ctrl_Active = 0) OR (@.TemplateActive = 0)
SET @.Active = 0
-- if the placeholder is still considered active,
check for duplicate checks of the same measure
-- on the same portfolio
IF @.Active = 1
BEGIN
-- look for active ordinary/manual checks that
cover the same measure and portfolio
-- although there really shouldn;t be any of
these!!
SELECT @.DUPLICATE_CHECKCOUNT = COUNT(CheckID)
FROM dbo.Checks
WHERE DBO.GET_CHECKMEASUREID(CheckID) =
@.MeasureID
AND PortfolioID =
@.PortfolioID
AND CheckID <>
@.CheckID
AND Active =
1
-- if we found an active ordinary/manual check,
use that instead of the placeholder
IF @.DUPLICATE_CHECKCOUNT > 0
SET @.Active = 0
END
IF (@.Active = 1) OR (@.ShowInActive=1)
SELECT @.Value1 =
DBO. GET_PLACEHOLDERVALUE(@.TemplateChecksType
Symbol, @.TemplateValue1,
@.Ctrl_Amt)
END
END
END
-- If it's a 'dynamic' placeholder check (with no template)
then NULL out the limit value as an indication to the
-- calling softwatre that the value neds computing and has not
been done by this routine. This is part of CHG109212, June 2004.
IF ((@.ChecksTypeSymbol = 'CHECKS_AUTO') AND (@.TemplateRef IS
NULL))
BEGIN
SET @.Value1 = NULL
SET @.Value2 = NULL
END
-- Don't allow templates or inactive checks to appear in the
result set for deal violations
-- for browsing, all checks will appear
IF (@.ChecksForDealViolations=1 AND @.CheckSymbol <>
'CHECK_LIMIT_TEMPLATE' AND (@.Active=1 OR @.ShowInActive=1)) OR
(@.ChecksForDealViolations=0 AND (@.Active=1 OR @.ShowInActive=1))
BEGIN
-- Insert into result table the values (which have been
overriden in the case of placeholder checks)
INSERT INTO @.CHECKSTAB
SELECT @.CheckID, @.PortfolioID, @.ClassID, @.MeasureID,
@.ChecksType, @.Value1, @.Value2, @.Message, @.MessageID, @.Severity,
@.ReviewDate,
@.ExpiryDate, @.AssetID, @.TemplateRef,
@.IsConditional, @.Active, @.Threshold, @.HasTransfers
END
FETCH NEXT FROM CHECK_CURSOR INTO
@.CheckID, @.PortfolioID, @.ClassID, @.MeasureID, @.ChecksType,
@.Value1, @.Value2, @.Message, @.MessageID, @.Severity, @.ReviewDate,
@.ExpiryDate,
@.AssetID, @.TemplateRef, @.IsConditional, @.Active,
@.Threshold, @.HasTransfers, @.CheckSymbol, @.ChecksTypeSymbol
END -- while
CLOSE CHECK_CURSOR
DEALLOCATE CHECK_CURSOR
IF @.ChecksForDealViolations = 1
SELECT * FROM @.CHECKSTAB ORDER BY PortfolioID
ELSE --return a formatted view for browsing checks
SELECT
DefnPortfolio.PortfolioName AS Portfolio,
Checks.MESSAGE AS Legend, -- DummyColumn
Checks.CheckID,
Class.Name AS Type,
ChecksType,
DefnPortfolioMeasureClass.Name AS Measure,
-- Checks.Message Description, -- DummyColumn
Checks.Severity,
Checks.REVIEWDATE AS Review,
Checks.EXPIRYDATE AS Expiry,
Checks.PortfolioID,
Checks.ClassID,
Checks.Value1,
Checks.Value2,
Checks.Active,
Checks.Threshold,
Checks.HasTransfers,
dbo.Asset.Code AS Currency,
(SELECT COUNT(1)
FROM dbo.Violation
WHERE Violation.CheckID = Checks.CheckID) AS
Violations,
DefnPortfolioMeasureClass.MeasureID AS MeasureID,
Checks.AssetID,
IsConditional Conditional,
Checks.Message Details
FROM @.CHECKSTAB Checks
INNER JOIN dbo.Class
ON Checks.CLASSID = Class.ClassID
LEFT OUTER JOIN dbo.Asset
ON Checks.ASSETID = Asset.AssetID
LEFT OUTER JOIN dbo.DefnPortfolio
INNER JOIN dbo.Portfolio
ON DefnPortfolio.PfolDefnID = Portfolio.ClassID
ON Checks.PORTFOLIOID = Portfolio.PortfolioID
LEFT OUTER JOIN dbo.DefnPortfolioMeasureClass
ON Checks.MEASUREID =
DefnPortfolioMeasureClass.MeasureID
END

Friday, February 17, 2012

CSV rendering is missing first detail row

For one report we've designed, an HTML rendering will produce 3 detail
records. When this same report with the same parameters is rendered in CSV,
the first detail row is missing from the output. All other aspects of the
export seem to work as expected.
This occurs with several reports we have but not all of them. This happens
when previewing in VS.NET, RS Manager, and on our live Web site. Other
formats do not drop the first detail record.
Is there any resolution to this problem?FYI: I experienced the same problem you described. Through trial and error I
determined that what was causing the problem was that I was grouping the
Details section of the Table. To work around this I added grouping to the SQL
code and removed grouping from the report detail.
Brad
"John Demar" wrote:
> For one report we've designed, an HTML rendering will produce 3 detail
> records. When this same report with the same parameters is rendered in CSV,
> the first detail row is missing from the output. All other aspects of the
> export seem to work as expected.
> This occurs with several reports we have but not all of them. This happens
> when previewing in VS.NET, RS Manager, and on our live Web site. Other
> formats do not drop the first detail record.
> Is there any resolution to this problem?

CSV rendering is missing first detail row

For one report we've designed, an HTML rendering will produce 3 detail
records. When this same report with the same parameters is rendered in CSV,
the first detail row is missing from the output. All other aspects of the
export seem to work as expected.
This occurs with several reports we have but not all of them. This happens
when previewing in VS.NET, RS Manager, and on our live Web site. Other
formats do not drop the first detail record.
Any ideas? I can't seem to find anyone else that has run across this
problem in the groups.I continue to have this problem and cannot find any answers. Is there a
problem with the CSV rendering extension?
"John Demar" wrote:
> For one report we've designed, an HTML rendering will produce 3 detail
> records. When this same report with the same parameters is rendered in CSV,
> the first detail row is missing from the output. All other aspects of the
> export seem to work as expected.
> This occurs with several reports we have but not all of them. This happens
> when previewing in VS.NET, RS Manager, and on our live Web site. Other
> formats do not drop the first detail record.
> Any ideas? I can't seem to find anyone else that has run across this
> problem in the groups.
>|||John,
I am also seeing the same results with the missing first line. Does anyone
know if this is a known issue or just a setting that can be set?
"John Demar" wrote:
> I continue to have this problem and cannot find any answers. Is there a
> problem with the CSV rendering extension?
> "John Demar" wrote:
> > For one report we've designed, an HTML rendering will produce 3 detail
> > records. When this same report with the same parameters is rendered in CSV,
> > the first detail row is missing from the output. All other aspects of the
> > export seem to work as expected.
> >
> > This occurs with several reports we have but not all of them. This happens
> > when previewing in VS.NET, RS Manager, and on our live Web site. Other
> > formats do not drop the first detail record.
> >
> > Any ideas? I can't seem to find anyone else that has run across this
> > problem in the groups.
> >

CSV exporting issue

Hi,

I have a simple report with a table and 3 columns. I have used only the detail row of the table to display data from a simple dataset that has a stored procedure as the data source.

When I export it to CSV format, the names of the textboxes that are in the table column also gets exported in the first row. Is there a way to suppress this?

I have already tried setting DataElementOutput = NoOutput for the table and the textboxes but nothing works. Please do not give me the link of an earlier thread on the same topic because that doesnt provide the answer.

I have also tried setting DeviceInfo parameters in RSReportDesigner.config and rsreportserver.config (NoHeader=true) but none of them work even after restarting the machine and SQL Reporting Service.

If there is a way or an alternative, please let me know.

Thanks,

Shyam

There is another issue with CSV exporting.

I want every field to be wrapped around double quotes, so I have handled that in the SQL query itself. When I export to CSV, it adds 4 more double quotes to every field which means every field has 6 double quotes around it (3 to the left and 3 to the right). I also tried handling it in the report by appending Chr(34) and an explicit double quote in the field expression but all of them seem to give the same stupid result (6 double quotes).

Is there a way to work around this problem in SQL Reporting services?

It's very frustrating.

Shyam

|||

Thanks everybody for not responding. Hope it works on another machine.

Shyam

CSV exporting issue

Hi,

I have a simple report with a table and 3 columns. I have used only the detail row of the table to display data from a simple dataset that has a stored procedure as the data source.

When I export it to CSV format, the names of the textboxes that are in the table column also gets exported in the first row. Is there a way to suppress this?

I have already tried setting DataElementOutput = NoOutput for the table and the textboxes but nothing works. Please do not give me the link of an earlier thread on the same topic because that doesnt provide the answer.

I have also tried setting DeviceInfo parameters in RSReportDesigner.config and rsreportserver.config (NoHeader=true) but none of them work even after restarting the machine and SQL Reporting Service.

If there is a way or an alternative, please let me know.

Thanks,

Shyam

There is another issue with CSV exporting.

I want every field to be wrapped around double quotes, so I have handled that in the SQL query itself. When I export to CSV, it adds 4 more double quotes to every field which means every field has 6 double quotes around it (3 to the left and 3 to the right). I also tried handling it in the report by appending Chr(34) and an explicit double quote in the field expression but all of them seem to give the same stupid result (6 double quotes).

Is there a way to work around this problem in SQL Reporting services?

It's very frustrating.

Shyam

|||

Thanks everybody for not responding. Hope it works on another machine.

Shyam

CSV export missing row

Hello
Does any one have an explaination or work around for the missing first row
of data in csv export?
Please help!
Thanks
JessicaI am struggling with the same problem. Is there really no answer/help out
there?`
Thanks,
J. Schuetz.
"Jessica C" wrote:
> Hello
> Does any one have an explaination or work around for the missing first row
> of data in csv export?
> Please help!
> Thanks
> Jessica
>
>

CSV Export error

Hi,

After exporting a report to CSV format, when opening the file in Excel, all the data in a row comes into a single column, than spliting into different columns.

We can split into different columns using 'Text to columns' option from 'Data' Menu, but does not do defaultly as a CSV file is supposed to do.

Is this is bug with Reporting Service? Or am i missing something?

I am using release version of MS Reporting Service 2005.

Thanks,

Anobe

I experienced this problem too. The default setting is unicode, you have to specify ASCII for csv rendering. We were able to fix it by changing the config file.

File to change:

C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\rsreportserver.config

Before:

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering"/>

After:

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering">

<Configuration>

<DeviceInfo>

<Encoding>ASCII</Encoding>

</DeviceInfo>

</Configuration>

</Extension>

|||

Thanks buddy,

this was very helpful. I didn't do the exact way, since i cannot change the config file. So, i handled the situation in the code using System.Text.UniEncoding.

|||

hi anobe....

i am facing the same situation like u...i cant change the config file. so i am wondering how did u handled the situation

using the system.text.uniencoding ? could you please elobrate further

thanks bro

CSV Export error

Hi,

After exporting a report to CSV format, when opening the file in Excel, all the data in a row comes into a single column, than spliting into different columns.

We can split into different columns using 'Text to columns' option from 'Data' Menu, but does not do defaultly as a CSV file is supposed to do.

Is this is bug with Reporting Service? Or am i missing something?

I am using release version of MS Reporting Service 2005.

Thanks,

Anobe

I experienced this problem too. The default setting is unicode, you have to specify ASCII for csv rendering. We were able to fix it by changing the config file.

File to change:

C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\rsreportserver.config

Before:

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering"/>

After:

<Extension Name="CSV" Type="Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering">

<Configuration>

<DeviceInfo>

<Encoding>ASCII</Encoding>

</DeviceInfo>

</Configuration>

</Extension>

|||

Thanks buddy,

this was very helpful. I didn't do the exact way, since i cannot change the config file. So, i handled the situation in the code using System.Text.UniEncoding.

|||

hi anobe....

i am facing the same situation like u...i cant change the config file. so i am wondering how did u handled the situation

using the system.text.uniencoding ? could you please elobrate further

thanks bro

|||In case you didn't get your problem solved (or for others out there with the same problem):

I was having this problem too and changing the encoding of the report to ASCII (default is UTF8 I think) fixed the problem.

I am calling my report through the url, you can pass the encoding as a url parameter, for example:
http://reportservername/ReportServer/report?rs:Command=Render&rs:Format=CSV&rc:Encoding=ASCII