Showing posts with label inside. Show all posts
Showing posts with label inside. Show all posts

Thursday, March 29, 2012

CURSOR trouble (:

Hi All,

What i am trying to do is concatenate variable "@.Where" with CURSOR sql statement,inside a procedure . But, it doesn't seem to get the value for the @.Where. (I tried with DEBUGGING option of Query Analyzer also).

=============================================
SET @.Where = ''
if IsNull(@.Input1,NULL) <> NULL
Set @.Where = @.Where + " AND studentid='" + @.input1 +"'"

if isnull(@.Input2,NULL) <> NULL
Set @.Where = @.Where + " AND teacherid =' " + @.Input2 +"'"

DECLARE curs1 CURSOR SCROLL
FOR SELECT
*
FROM
school
WHERE
school ='ABC' + @.where
=============================================

It gives me all the Records inside the SCHOOL='ABC' ...

Please check my SQL Above and Could somebody tell me , how can I attach the VARIABLE with CURSOR sql statement ?

Please advice me..(:

Thanks !Well, looks like another day is over, so it is time to repeat the (same old) basic thing about SQL again.

You can NOT just put up part of a SQL Statement into a variable and then think the SQL compiler acutlly magically produces dynamic SQL out of it.

That simple.

In your example:

::DECLARE curs1 CURSOR SCROLL
::FOR SELECT
::*
::FROM
::school
::WHERE
::school ='ABC' + @.where

@.where will NOT be appened to the SQL statement. It will be part of the right part of the comparison.

So, if @.where consists of (example)

::AND studentid='22'

it will check whether schoon equals "ABC AND studentid='22'".

That simple.

If you want to execute a dynamic SQL thing, then do so. There are means for this. But otherwise, variables are variables, not some "post compiler magic thing that happens when you dance around the computer at night singing magic chants".

Interesting enough you are not alone. Lots of people think like this - as I said in the beginning, some typical (beginner) error like this pops up every second day. Most, though, stumble opver it before they get into using / abusing cursors.|||

SELECT *
FROM
school
WHERE
school ='ABC'
AND
( @.Input1 IS NULL OR @.Input1 = StudentID )
AND
( @.Input2 IS NULL OR @.Input2 = teacherID )
>>using / abusing cursors

So true.... many developers often try to solve T-SQL problems by using cursors, similar to the way they might program in other environments—working with one record at a time in sequential order. But this approach doesn't exploit the power of SQL Servers "engine", which is optimized for set-based processing. Cursors usually require considerably more code than their equivalent set-based solutions and are much less efficient.

If a cursor is the first thing that you think of when you face a T-SQL problem, you have some unlearning to do—you need to start thinking "set-based.

http://www.windowsitpro.com/SQLServer/Article/ArticleID/22431/22431.html|||Christmas is supposed to be about giving so here we go. Some good advice already provided (though not entirely correct). First of all cursor or no cursor and trying to concatenate a where clause or not why are you doing this: if IsNull(@.Input1,NULL) <> NULL ?

For one thing when ever evaluating NULL always use: IF @.Input1 IS NULL or in your specific example IF @.Input1 IS NOT NULL

As for using the ISNULL function I suggest that you use this only when you suspect that the value is null or perhaps in your case an empty string in which case thew correct syntax would be: IF ISNULL(@.Input1, '') <> ''

Also, regardless of if you really need a cursor or not from the example you have provided you can generate the select as follows:

SELECT * FROM school
WHERE school = 'ABC' AND studentid LIKE ISNULL(@.Input1, '') + '%' AND teacherid LIKE ISNULL(@.Input2, '') + '%' ...

Now if you still really feel that you have to concatenate a where clause it can in fact be done but it is ugly! It works like this (but is only viable for returning a result set, in other words you cannot use it for a CURSOR!):

EXEC('SELECT * FROM school WHERE ' + @.Where)

Last but not least, as one of the other respondents suggested CURSOR's should be avoided at all costs and as such there are a number of other ways to apply updates to a group of records with some pretty flexible conditional logic.

Step 1: select the target records into a temporary table i.e.

SELECT [primary_key_field] INTO #target
FROM school WHERE (school = 'ABC')
AND (studentid LIKE ISNULL(@.Input1, '') + '%')
AND (teacherid LIKE ISNULL(@.Input2, '') + '%') ...

Now that you have the keyset available you can do a simple update to all the records in the resultset as follows:

UDPATE school
SET [whatever_field] = [whatever_value]
FROM school, #target
WHERE school.[primary_key_field] = #target.[primary_key_field]

For more sophisitcated updates you can use a flavour of the CASE in sql such as

SET [whatever_field] = CASE WHEN [condition1] = True THEN
value1
WHEN [condition2] = True THEN
value2
...
END

for as many fields as it takes.

Hope this helps.

Cheers

Gary|||Thanks to you all people up there...it solved my problem...Have a wonderful Holidays...:)sql

cursor to alter table, add columns

Friends,
I am trying to use a cursor inside a stored procedure to add columns to a
temp table. Can anyone tell me how to fix the following code so the cursor
will feed new column names to the alter table statement?
The code fails when I try to use a variable as a column name in the alter
table statement.
Thanks for your help ...
DECLARE @.strVar varchar(7)
If object_id('tempdb..#temptbl') is not null
begin
drop table #temptbl
end
Create Table #temptbl
(sku varchar(15) null)
DECLARE mycursor CURSOR
FOR
SELECT colA
FROM PermTable
OPEN mycursor
FETCH NEXT
FROM mycursor
INTO @.strVar
alter table #temptbl
add
@.strVAr varchar(20) null
WHILE @.@.fetch_status = 0
BEGIN
FETCH NEXT
FROM mycursor
INTO @.strVar
alter table #temptbl
add
@.strVar varchar(20) null
END
CLOSE mycursor
DEALLOCATE mycursorWhy in the world would you ever want to do this'''?
nevermind.......
CREATE TABLE #thisisstupid(colname VARCHAR(256))
GO
INSERT #thisisstupid(colname)
SELECT 'col1' UNION ALL
SELECT 'col2' UNION ALL
SELECT 'col3' UNION ALL
SELECT 'col4'
DECLARE @.thisisstupider VARCHAR(4000)
SELECT @.thisisstupider = ''
SELECT @.thisisstupider = @.thisisstupider + colname + ' VARCHAR(20), '
FROM #thisisstupid
SELECT @.thisisstupider = 'ALTER TABLE #thisisstupid ADD ' + @.thisisstupider
SELECT @.thisisstupider = LEFT(@.thisisstupider,LEN(@.thisisstupider
)-1)
EXEC(@.thisisstupider)
SELECT * FROM #thisisstupid
DROP TABLE #thisisstupid
GO
"bill_morgan_3333" <billmorgan3333@.discussions.microsoft.com> wrote in
message news:50997181-3CC0-45EE-97FE-7C389EDB6909@.microsoft.com...
> Friends,
> I am trying to use a cursor inside a stored procedure to add columns to a
> temp table. Can anyone tell me how to fix the following code so the cursor
> will feed new column names to the alter table statement?
> The code fails when I try to use a variable as a column name in the alter
> table statement.
> Thanks for your help ...
>
> DECLARE @.strVar varchar(7)
> If object_id('tempdb..#temptbl') is not null
> begin
> drop table #temptbl
> end
> Create Table #temptbl
> (sku varchar(15) null)
> DECLARE mycursor CURSOR
> FOR
> SELECT colA
> FROM PermTable
> OPEN mycursor
> FETCH NEXT
> FROM mycursor
> INTO @.strVar
> alter table #temptbl
> add
> @.strVAr varchar(20) null
> WHILE @.@.fetch_status = 0
> BEGIN
> FETCH NEXT
> FROM mycursor
> INTO @.strVar
> alter table #temptbl
> add
> @.strVar varchar(20) null
> END
> CLOSE mycursor
> DEALLOCATE mycursor
>|||If you are so disgusted, why even reply? Keep your "stupid" remarks to
yourself.|||You may need to do this when you want the procedure to return a "pivot table
"
- i.e., the values in one column need to become column headers in the
returned records -in the meantime I was able to find a guy at a local compan
y
who is familiar with this technique, using a cursor. It does involve storin
g
the entire ALTER TABLE statement ( + a variable for the new column value)
inside a variable, as you've done below.
Inside each loop the new column value is updated and the sp_executesql is
executed to run the ALTER TABLE string.
Thanks for your reply ...
bill morgan
"Derrick Leggett" wrote:

> Why in the world would you ever want to do this'''?
> nevermind.......
>
> CREATE TABLE #thisisstupid(colname VARCHAR(256))
> GO
> INSERT #thisisstupid(colname)
> SELECT 'col1' UNION ALL
> SELECT 'col2' UNION ALL
> SELECT 'col3' UNION ALL
> SELECT 'col4'
> DECLARE @.thisisstupider VARCHAR(4000)
> SELECT @.thisisstupider = ''
> SELECT @.thisisstupider = @.thisisstupider + colname + ' VARCHAR(20), '
> FROM #thisisstupid
> SELECT @.thisisstupider = 'ALTER TABLE #thisisstupid ADD ' + @.thisisstupide
r
> SELECT @.thisisstupider = LEFT(@.thisisstupider,LEN(@.thisisstupider
)-1)
> EXEC(@.thisisstupider)
> SELECT * FROM #thisisstupid
> DROP TABLE #thisisstupid
> GO
> "bill_morgan_3333" <billmorgan3333@.discussions.microsoft.com> wrote in
> message news:50997181-3CC0-45EE-97FE-7C389EDB6909@.microsoft.com...
>
>|||Because normally people do this for a stupid reason. :) He actually has an
interesting reason for doing it. Calm down guy. It's not the end of the
world. He took it a little better than you. And, it is stupid that you
would have to do this for a PIVOT table in SQL Server. It's also
unfortunate in 2005 that they haven't fixed this. You still need to
hardcode the values for the columns, which IS STUPID!!!!! And, I won't keep
my stupid remarks to myself. People need to think about what they are
doing.
The MS reason for the pivot table in 2005 being written in that format is
because "it would cause problems with the optimizer otherwise". That really
doesn't cut it. The pivot is a great idea. The way they implemented it
though forces the everyday user to resort to dynamic SQL for it to be truly
useful. That's a shame. They should have a warning in Books Online about
the optimizer and plan generator having some issues with a dynamic comic
list, not just exclude the functionality completely.
"bd" <bryce_dooley123@.yahoo.com> wrote in message
news:1110478752.721077.32400@.o13g2000cwo.googlegroups.com...
> If you are so disgusted, why even reply? Keep your "stupid" remarks to
> yourself.
>sql

Tuesday, March 27, 2012

Cursor inside another cursor, or...?

I'm doing something like the following, but I need to insert a few
functions.
1) I would like to be able to insert each orderline from our
INVOICELINEARCHIVE in the email text below the T&T number - like:
*Pseudo code*
For Each Line in INVOICELINEARCHIVE, Where INVOICELINEARCHIVE.NUMBER =
@.OrderNumber
Print OrderText, OrderAmount, OrderPrice
Next
- or this might be done by a SELECT ? Or another Cursor somehow?
- I have used the SELECT with XPSMTP before, like:
SELECT @.message = @.message + '<TR><TD>' + ORDERHEADARCHIVE.NUMBER +
'</TD><TD>' + ORDERHEADARCHIVE.NAME + '</TD></TR>'
FROM ***
WHERE ***
(A) Tried something like this by comparing the variable @.OrderNumber with my
ORDERHEADARCHIVE.ORDERNUMBER in the WHERE statement, but it wouldnt work...
2) I would further more like to be able to insert multipe T&T numbers into
the same email - this is when an order is split over more than one package.
This is what I have right now:
--
CREATE PROC SP_TRACKNTRACE
AS
SET NOCOUNT ON
DECLARE @.CustomorName varchar(100), @.OrderNumber varchar(10), @.InvoiceNumber
varchar(20), @.EmailAddress varchar(150), @.TrackTraceNumber varchar(20),
@.NEXT_KEY int,
@.message varchar(4000), @.msg nvarchar(4000), @.From varchar(400), @.FromName
varchar(400), @.ReplyTo varchar(300), @.BCC varchar(300), @.RecepientList
varchar(400),
@.Subject varchar(300), @.RC int, @.body varchar(3000), @.title varchar(80),
@.header varchar(10), @.signature varchar(10)
SET @.BCC = 'netsales@.domain.com'
SET @.Subject = 'Deliverystatus - Track & Trace'
DECLARE SEND_EMAIL CURSOR
FOR
SELECT INVOICEHEADARCHIVE.NAME,
INVOICEHEADARCHIVE.EMAIL,
IT_TRACKNTRACE.ORDERNUMBER,
IT_TRACKNTRACE.INVOICENO,
IT_TRACKNTRACE.TRACKNTRACE
FROM INVOICEHEADARCHIVE,IT_TRACKNTRACE
WHERE INVOICEHEADARCHIVE.EMAIL like '%_@._%.__%'
AND IT_TRACKNTRACE.TRACKNTRACE <> ''
AND ISNUMERIC(IT_TRACKNTRACE.INVOICENO) > 0
AND INVOICEHEADARCHIVE.INVOICENO = CONVERT(INT,IT_TRACKNTRACE.INVOICENO)
AND INVOICEHEADARCHIVE.INVOICEDATE > DATEADD(DAY,-1,GETDATE())
OPEN SEND_EMAIL
FETCH NEXT FROM SEND_EMAIL INTO @.CustomorName, @.EmailAddress, @.OrderNumber,
@.InvoiceNumber, @.TrackTraceNumber
WHILE (@.@.FETCH_STATUS = 0)
BEGIN
BEGIN
SET @.FromName = 'Company Name'
SET @.From = 'netsales@.domain.com'
SET @.msg = N'<HTML><font face="Arial" size="2">Dear ' +
@.CustomorName + ','
SET @.msg = @.msg + N'<BR><BR>'
SET @.msg = @.msg + N'Today we send you ordernumber ' + @.OrderNumber + ' ,
invoicenumber ' + @.InvoiceNumber + '.'
SET @.msg = @.msg + N'<BR><BR>'
SET @.msg = @.msg + N'Your package has Track & Trace number: ' +
@.TrackTraceNumber + '.'
--** This is where I wuld like to add all T&T numbers concerning the order
SET @.msg = @.msg + N'<BR><BR><BR>'
--** This is where I would like some lines from a table by a SELECT query or
something like it (A)
SET @.msg = @.msg + N'Best Regards'
SET @.msg = @.msg + N'<BR><BR>'
SET @.msg = @.msg + N'My Company Name'
SET @.msg = @.msg + N'<BR>'
SET @.msg = @.msg + N'<a href="http://links.10026.com/?link=http://www.domain.com">www.domain.com</a>'
SET @.msg = @.msg + N'</font></HTML>'
END
SET @.ReplyTo = @.From
EXEC @.rc = master.dbo.xp_smtp_sendmail
@.FROM = @.From,
@.FROM_NAME = @.FromName,
@.TO = @.EmailAddress,
@.BCC = @.BCC,
@.replyto = @.ReplyTo,
@.subject = @.Subject,
@.message = @.msg,
@.type = N'text/html',
@.server = N'192.168.0.1'
FETCH NEXT FROM SEND_EMAIL INTO @.CustomerName, @.EmailAddress,
@.OrderNumber, @.InvoiceNumber, @.TrackTraceNumber
END
CLOSE SEND_EMAIL
DEALLOCATE SEND_EMAIL
--
Thanx
Jakob"Sokrates" (somebody@.somewhere.earth) writes:
> I'm doing something like the following, but I need to insert a few
> functions.
> 1) I would like to be able to insert each orderline from our
> INVOICELINEARCHIVE in the email text below the T&T number - like:
> *Pseudo code*
> For Each Line in INVOICELINEARCHIVE, Where INVOICELINEARCHIVE.NUMBER =
> @.OrderNumber
> Print OrderText, OrderAmount, OrderPrice
> Next
> - or this might be done by a SELECT ? Or another Cursor somehow?
> - I have used the SELECT with XPSMTP before, like:
> SELECT @.message = @.message + '<TR><TD>' + ORDERHEADARCHIVE.NUMBER +
> '</TD><TD>' + ORDERHEADARCHIVE.NAME + '</TD></TR>'
> FROM ***
> WHERE ***
> (A) Tried something like this by comparing the variable @.OrderNumber
> with my ORDERHEADARCHIVE.ORDERNUMBER in the WHERE statement, but it
> wouldnt work...
"It wouldn't work" means what? You got an error message? You got an
unexpected result? It is always recommendable to be specific when you
post a question, as it easier for people to help you.
In any case, I am not really sure what the question is, but starting
from the subject line, yes you can nest cursors. And if I understand
this talk about T&T, it seems that a cursor is what you need to include
them all in the message.
However, I think you are on the wrong path when you try to send this from
SQL Server. When you build the message, you must assemble the text
in a varchar(8000) variable, which means that 8000 bytes is the space
you have, for content and HTML tags and all.
It's probably better to have a client app, to read the data and then
compose the HTML thing. You don't run the risk that the mail is cut
in the middle, and the coding is likely to be easier.
I also would like to point out that if this mail could be sent to
anyone, it's not a good idea to sent mail in HTML format only. Not
everyone uses mail readers that understand HTML. And some people may
have spam filterns that nukes everything which is in HTML only. So
probably you should generate a text-only message, or a
multipart/alternative with both text and HTML.
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp

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..tempbalhistory1Did you write this? Or was it given to you?

You don't need a cursor at all for this (although I'm having trouble trying to figure out what you're trying to do)...

Lose Cursor 1 altogethr.

Use the SELECT (which already has the table in it you want) as the Portion of the INSERT Statement...that's it...

Except for this

where( convert (int,@.amount) <= -50
or @.amount * -1 > @.before * .02)
and @.type = 'P'

Which I have no idea what you want.

I expect all you need to do is add that to the select

Cursor in Trigger

Hi All, I have a problem when I try to use a Cursor for update inside a
trigger, the problem is that when I try to update another table using the
values for temporary tables "inserted" or "deleted" appers this error: "For
update cannot be specified on a read only cursor. Error 16957. Severity 16"
I hope some one can help me
Note:
This problem does not occurs in SQL 7, just in 2000
"Ton" wrote:

> Hi All, I have a problem when I try to use a Cursor for update inside a
> trigger, the problem is that when I try to update another table using the
> values for temporary tables "inserted" or "deleted" appers this error: "For
> update cannot be specified on a read only cursor. Error 16957. Severity 16"
> I hope some one can help me
|||Ton wrote:
> Hi All, I have a problem when I try to use a Cursor for update inside
> a trigger, the problem is that when I try to update another table
> using the values for temporary tables "inserted" or "deleted" appers
> this error: "For update cannot be specified on a read only cursor.
> Error 16957. Severity 16"
> I hope some one can help me
Post your code please.
David Gugick
Imceda Software
www.imceda.com
|||inserted and deleted logical tables r readonly.
U cant use them in an update cursor
"Ton" <Ton@.discussions.microsoft.com> wrote in message
news:69354871-442B-48DF-8C98-D544C3FE11AB@.microsoft.com...
> Hi All, I have a problem when I try to use a Cursor for update inside a
> trigger, the problem is that when I try to update another table using the
> values for temporary tables "inserted" or "deleted" appers this error:
"For
> update cannot be specified on a read only cursor. Error 16957. Severity
16"
> I hope some one can help me
|||USE FICS
go
-- Type: Trigger
-- Name: trIFisTrackerItem011
CREATE TRIGGER trIFisTrackerItem011
ON TRACKERITEM011
WITH ENCRYPTION
FOR INSERT AS
/*----*/
/* Proposito.: Trigger de INSERT */
/*----*/
/* Historial.: */
/* */
/* */
/*----*/
/*
** General Variable
*/
DECLARE @.numrows int,
@.errno int,
@.errmsg varchar(255),
@.INSERT T_udtActionType,
@.UPDATE T_udtActionType,
@.DELETE T_udtActionType,
@.SELECT T_udtActionType,
@.REPORT T_udtActionType
/*
** Process Variable
*/
DECLARE @.SerialLog T_udtIDStrAlt,
@.ProductLog T_udtIDStrAlt,
@.RegionLog T_udtIDStrAlt,
@.LocationLog T_udtIDStrAlt,
@.Reference1 T_udtIDStrAlt,
@.TimeStampLog T_udtDateTime
/*
** Affected rows
*/
SELECT @.numrows = @.@.ROWCOUNT
/*
** If have affected rows
*/
IF @.numrows = 0
RETURN
SET NOCOUNT ON
/*
** Transaction type
*/
SELECT @.INSERT = 1,
@.UPDATE = 2,
@.DELETE = 3,
@.SELECT = 4,
@.REPORT = 5
/*
**=========================================
** BEGIN PROCESS
**=========================================
*/
/*
** Cursor declare for inserted rows
*/
DECLARE TrackerItem011_Cursor SCROLL CURSOR
FOR SELECT TKI.SERIALLOG_VAL0,
TKI.PRODUCTLOG_VAL0,
TKI.REGIONLOG_VAL0,
TKI.LOCATIONLOG_VAL0,
TKI.REFERENCELOG_VAL0,
TKI.timestamp
FROM TRACKERITEM011 TKI
WHERE ISNULL(TKI.InTracker, 0) = 0
AND TKI.SERIALLOG_VAL0 IS NOT NULL
AND EXISTS(SELECT 1
FROM Inserted INS
WHERE INS.timeStamp = TKI.timeStamp
AND INS.project = TKI.project
)
FOR UPDATE OF TKI.InTracker
/*
** Open cursor
*/
OPEN TrackerItem011_Cursor
/*
** First record
*/
FETCH NEXT FROM TrackerItem011_Cursor
INTO @.SerialLog,
@.ProductLog,
@.RegionLog,
@.LocationLog,
@.Reference1,
@.TimeStampLog
/*
** Loop over cursor
*/
WHILE @.@.FETCH_STATUS = 0
BEGIN
/*
** Generate Tracker Item
*/
EXECUTE spFisXSetTrackerItem @.SerialLog, @.ProductLog, @.RegionLog,
@.LocationLog, @.TimeStampLog, @.Reference1, NULL, NULL, 0
/*::::::::::::::::::::::::::::::::::::::::::::*/
/* Check for error */
/*::::::::::::::::::::::::::::::::::::::::::::*/
IF @.@.ERROR <> 0
BEGIN
SELECT @.errno = 80001,
@.errmsg = "Transaction Fault into 'TRACKERITEM011' table
while update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
ISNULL(@.RegionLog, 'NULL') + "'."
GOTO errHandler
END
/*
** Update this record
*/
UPDATE TRACKERITEM011
SET InTracker = 1
WHERE CURRENT OF TrackerItem011_Cursor
/*
** Next record
*/
FETCH NEXT FROM TrackerItem011_Cursor
INTO @.SerialLog,
@.ProductLog,
@.RegionLog,
@.LocationLog,
@.Reference1,
@.TimeStampLog
END
/*
** Destroy cursor
*/
CLOSE TrackerItem011_Cursor
DEALLOCATE TrackerItem011_Cursor
/*::::::::::::::::::::::::::::::::::::::::::::*/
/* Check for error */
/*::::::::::::::::::::::::::::::::::::::::::::*/
IF @.@.ERROR <> 0
BEGIN
SELECT @.errno = 80001,
@.errmsg = "Transaction Fault into 'TRACKERITEM011' table while
update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
ISNULL(@.RegionLog, 'NULL') + "' Location='" + ISNULL(@.LocationLog, 'NULL') +
"'."
GOTO errHandler
END
/*
** Exit point
*/
ExitPoint:
SET NOCOUNT OFF
RETURN
/*
** Handle Error
*/
errHandler:
EXEC master.dbo.xp_logevent @.errno, @.errmsg, informational
RAISERROR @.errno @.errmsg
ROLLBACK TRANSACTION
GOTO ExitPoint
"David Gugick" wrote:

> Ton wrote:
> Post your code please.
> --
> David Gugick
> Imceda Software
> www.imceda.com
>
|||Review the infomation in BOL under the topic "Implicit cursor conversions".
According to this, your cursor is implicitly converted to a static cursor
(which is not updateable) due to the query used.
"Ton" <Ton@.discussions.microsoft.com> wrote in message
news:178BF62D-9B73-453E-838F-07E72A012A18@.microsoft.com...
> USE FICS
> go
> -- Type: Trigger
> -- Name: trIFisTrackerItem011
>
> CREATE TRIGGER trIFisTrackerItem011
> ON TRACKERITEM011
> WITH ENCRYPTION
> FOR INSERT AS
>
/*----
*/
> /* Proposito.: Trigger de INSERT
*/
>
/*----
*/
> /* Historial.:
*/
> /*
*/
> /*
*/
>
/*----
*/
> /*
> ** General Variable
> */
> DECLARE @.numrows int,
> @.errno int,
> @.errmsg varchar(255),
> @.INSERT T_udtActionType,
> @.UPDATE T_udtActionType,
> @.DELETE T_udtActionType,
> @.SELECT T_udtActionType,
> @.REPORT T_udtActionType
> /*
> ** Process Variable
> */
> DECLARE @.SerialLog T_udtIDStrAlt,
> @.ProductLog T_udtIDStrAlt,
> @.RegionLog T_udtIDStrAlt,
> @.LocationLog T_udtIDStrAlt,
> @.Reference1 T_udtIDStrAlt,
> @.TimeStampLog T_udtDateTime
> /*
> ** Affected rows
> */
> SELECT @.numrows = @.@.ROWCOUNT
> /*
> ** If have affected rows
> */
> IF @.numrows = 0
> RETURN
> SET NOCOUNT ON
> /*
> ** Transaction type
> */
> SELECT @.INSERT = 1,
> @.UPDATE = 2,
> @.DELETE = 3,
> @.SELECT = 4,
> @.REPORT = 5
> /*
> **=========================================
> ** BEGIN PROCESS
> **=========================================
> */
> /*
> ** Cursor declare for inserted rows
> */
> DECLARE TrackerItem011_Cursor SCROLL CURSOR
> FOR SELECT TKI.SERIALLOG_VAL0,
> TKI.PRODUCTLOG_VAL0,
> TKI.REGIONLOG_VAL0,
> TKI.LOCATIONLOG_VAL0,
> TKI.REFERENCELOG_VAL0,
> TKI.timestamp
> FROM TRACKERITEM011 TKI
> WHERE ISNULL(TKI.InTracker, 0) = 0
> AND TKI.SERIALLOG_VAL0 IS NOT NULL
> AND EXISTS(SELECT 1
> FROM Inserted INS
> WHERE INS.timeStamp = TKI.timeStamp
> AND INS.project = TKI.project
> )
> FOR UPDATE OF TKI.InTracker
> /*
> ** Open cursor
> */
> OPEN TrackerItem011_Cursor
> /*
> ** First record
> */
> FETCH NEXT FROM TrackerItem011_Cursor
> INTO @.SerialLog,
> @.ProductLog,
> @.RegionLog,
> @.LocationLog,
> @.Reference1,
> @.TimeStampLog
> /*
> ** Loop over cursor
> */
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> /*
> ** Generate Tracker Item
> */
> EXECUTE spFisXSetTrackerItem @.SerialLog, @.ProductLog, @.RegionLog,
> @.LocationLog, @.TimeStampLog, @.Reference1, NULL, NULL, 0
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> /* Check for error */
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> IF @.@.ERROR <> 0
> BEGIN
> SELECT @.errno = 80001,
> @.errmsg = "Transaction Fault into 'TRACKERITEM011' table
> while update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') +
"'
> Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
> ISNULL(@.RegionLog, 'NULL') + "'."
> GOTO errHandler
> END
> /*
> ** Update this record
> */
> UPDATE TRACKERITEM011
> SET InTracker = 1
> WHERE CURRENT OF TrackerItem011_Cursor
> /*
> ** Next record
> */
> FETCH NEXT FROM TrackerItem011_Cursor
> INTO @.SerialLog,
> @.ProductLog,
> @.RegionLog,
> @.LocationLog,
> @.Reference1,
> @.TimeStampLog
> END
> /*
> ** Destroy cursor
> */
> CLOSE TrackerItem011_Cursor
> DEALLOCATE TrackerItem011_Cursor
>
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> /* Check for error */
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> IF @.@.ERROR <> 0
> BEGIN
> SELECT @.errno = 80001,
> @.errmsg = "Transaction Fault into 'TRACKERITEM011' table
while
> update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
> Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
> ISNULL(@.RegionLog, 'NULL') + "' Location='" + ISNULL(@.LocationLog, 'NULL')
+[vbcol=seagreen]
> "'."
> GOTO errHandler
> END
> /*
> ** Exit point
> */
> ExitPoint:
> SET NOCOUNT OFF
> RETURN
> /*
> ** Handle Error
> */
> errHandler:
> EXEC master.dbo.xp_logevent @.errno, @.errmsg, informational
> RAISERROR @.errno @.errmsg
> ROLLBACK TRANSACTION
> GOTO ExitPoint
>
> "David Gugick" wrote:

Sunday, March 25, 2012

Cursor in Trigger

Hi All, I have a problem when I try to use a Cursor for update inside a
trigger, the problem is that when I try to update another table using the
values for temporary tables "inserted" or "deleted" appers this error: "For
update cannot be specified on a read only cursor. Error 16957. Severity 16"
I hope some one can help meNote:
This problem does not occurs in SQL 7, just in 2000
"Ton" wrote:
> Hi All, I have a problem when I try to use a Cursor for update inside a
> trigger, the problem is that when I try to update another table using the
> values for temporary tables "inserted" or "deleted" appers this error: "For
> update cannot be specified on a read only cursor. Error 16957. Severity 16"
> I hope some one can help me|||Ton wrote:
> Hi All, I have a problem when I try to use a Cursor for update inside
> a trigger, the problem is that when I try to update another table
> using the values for temporary tables "inserted" or "deleted" appers
> this error: "For update cannot be specified on a read only cursor.
> Error 16957. Severity 16"
> I hope some one can help me
Post your code please.
--
David Gugick
Imceda Software
www.imceda.com|||inserted and deleted logical tables r readonly.
U cant use them in an update cursor
"Ton" <Ton@.discussions.microsoft.com> wrote in message
news:69354871-442B-48DF-8C98-D544C3FE11AB@.microsoft.com...
> Hi All, I have a problem when I try to use a Cursor for update inside a
> trigger, the problem is that when I try to update another table using the
> values for temporary tables "inserted" or "deleted" appers this error:
"For
> update cannot be specified on a read only cursor. Error 16957. Severity
16"
> I hope some one can help me|||USE FICS
go
---
-- Type: Trigger
-- Name: trIFisTrackerItem011
---
CREATE TRIGGER trIFisTrackerItem011
ON TRACKERITEM011
WITH ENCRYPTION
FOR INSERT AS
/*----*/
/* Proposito.: Trigger de INSERT */
/*----*/
/* Historial.: */
/* */
/* */
/*----*/
/*
** General Variable
*/
DECLARE @.numrows int,
@.errno int,
@.errmsg varchar(255),
@.INSERT T_udtActionType,
@.UPDATE T_udtActionType,
@.DELETE T_udtActionType,
@.SELECT T_udtActionType,
@.REPORT T_udtActionType
/*
** Process Variable
*/
DECLARE @.SerialLog T_udtIDStrAlt,
@.ProductLog T_udtIDStrAlt,
@.RegionLog T_udtIDStrAlt,
@.LocationLog T_udtIDStrAlt,
@.Reference1 T_udtIDStrAlt,
@.TimeStampLog T_udtDateTime
/*
** Affected rows
*/
SELECT @.numrows = @.@.ROWCOUNT
/*
** If have affected rows
*/
IF @.numrows = 0
RETURN
SET NOCOUNT ON
/*
** Transaction type
*/
SELECT @.INSERT = 1,
@.UPDATE = 2,
@.DELETE = 3,
@.SELECT = 4,
@.REPORT = 5
/*
**=========================================** BEGIN PROCESS
**=========================================*/
/*
** Cursor declare for inserted rows
*/
DECLARE TrackerItem011_Cursor SCROLL CURSOR
FOR SELECT TKI.SERIALLOG_VAL0,
TKI.PRODUCTLOG_VAL0,
TKI.REGIONLOG_VAL0,
TKI.LOCATIONLOG_VAL0,
TKI.REFERENCELOG_VAL0,
TKI.timestamp
FROM TRACKERITEM011 TKI
WHERE ISNULL(TKI.InTracker, 0) = 0
AND TKI.SERIALLOG_VAL0 IS NOT NULL
AND EXISTS(SELECT 1
FROM Inserted INS
WHERE INS.timeStamp = TKI.timeStamp
AND INS.project = TKI.project
)
FOR UPDATE OF TKI.InTracker
/*
** Open cursor
*/
OPEN TrackerItem011_Cursor
/*
** First record
*/
FETCH NEXT FROM TrackerItem011_Cursor
INTO @.SerialLog,
@.ProductLog,
@.RegionLog,
@.LocationLog,
@.Reference1,
@.TimeStampLog
/*
** Loop over cursor
*/
WHILE @.@.FETCH_STATUS = 0
BEGIN
/*
** Generate Tracker Item
*/
EXECUTE spFisXSetTrackerItem @.SerialLog, @.ProductLog, @.RegionLog,
@.LocationLog, @.TimeStampLog, @.Reference1, NULL, NULL, 0
/*::::::::::::::::::::::::::::::::::::::::::::*/
/* Check for error */
/*::::::::::::::::::::::::::::::::::::::::::::*/
IF @.@.ERROR <> 0
BEGIN
SELECT @.errno = 80001,
@.errmsg = "Transaction Fault into 'TRACKERITEM011' table
while update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
ISNULL(@.RegionLog, 'NULL') + "'."
GOTO errHandler
END
/*
** Update this record
*/
UPDATE TRACKERITEM011
SET InTracker = 1
WHERE CURRENT OF TrackerItem011_Cursor
/*
** Next record
*/
FETCH NEXT FROM TrackerItem011_Cursor
INTO @.SerialLog,
@.ProductLog,
@.RegionLog,
@.LocationLog,
@.Reference1,
@.TimeStampLog
END
/*
** Destroy cursor
*/
CLOSE TrackerItem011_Cursor
DEALLOCATE TrackerItem011_Cursor
/*::::::::::::::::::::::::::::::::::::::::::::*/
/* Check for error */
/*::::::::::::::::::::::::::::::::::::::::::::*/
IF @.@.ERROR <> 0
BEGIN
SELECT @.errno = 80001,
@.errmsg = "Transaction Fault into 'TRACKERITEM011' table while
update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
ISNULL(@.RegionLog, 'NULL') + "' Location='" + ISNULL(@.LocationLog, 'NULL') +
"'."
GOTO errHandler
END
/*
** Exit point
*/
ExitPoint:
SET NOCOUNT OFF
RETURN
/*
** Handle Error
*/
errHandler:
EXEC master.dbo.xp_logevent @.errno, @.errmsg, informational
RAISERROR @.errno @.errmsg
ROLLBACK TRANSACTION
GOTO ExitPoint
"David Gugick" wrote:
> Ton wrote:
> > Hi All, I have a problem when I try to use a Cursor for update inside
> > a trigger, the problem is that when I try to update another table
> > using the values for temporary tables "inserted" or "deleted" appers
> > this error: "For update cannot be specified on a read only cursor.
> > Error 16957. Severity 16"
> >
> > I hope some one can help me
> Post your code please.
> --
> David Gugick
> Imceda Software
> www.imceda.com
>|||Review the infomation in BOL under the topic "Implicit cursor conversions".
According to this, your cursor is implicitly converted to a static cursor
(which is not updateable) due to the query used.
"Ton" <Ton@.discussions.microsoft.com> wrote in message
news:178BF62D-9B73-453E-838F-07E72A012A18@.microsoft.com...
> USE FICS
> go
> ---
> -- Type: Trigger
> -- Name: trIFisTrackerItem011
> ---
>
> CREATE TRIGGER trIFisTrackerItem011
> ON TRACKERITEM011
> WITH ENCRYPTION
> FOR INSERT AS
>
/*----
*/
> /* Proposito.: Trigger de INSERT
*/
>
/*----
*/
> /* Historial.:
*/
> /*
*/
> /*
*/
>
/*----
*/
> /*
> ** General Variable
> */
> DECLARE @.numrows int,
> @.errno int,
> @.errmsg varchar(255),
> @.INSERT T_udtActionType,
> @.UPDATE T_udtActionType,
> @.DELETE T_udtActionType,
> @.SELECT T_udtActionType,
> @.REPORT T_udtActionType
> /*
> ** Process Variable
> */
> DECLARE @.SerialLog T_udtIDStrAlt,
> @.ProductLog T_udtIDStrAlt,
> @.RegionLog T_udtIDStrAlt,
> @.LocationLog T_udtIDStrAlt,
> @.Reference1 T_udtIDStrAlt,
> @.TimeStampLog T_udtDateTime
> /*
> ** Affected rows
> */
> SELECT @.numrows = @.@.ROWCOUNT
> /*
> ** If have affected rows
> */
> IF @.numrows = 0
> RETURN
> SET NOCOUNT ON
> /*
> ** Transaction type
> */
> SELECT @.INSERT = 1,
> @.UPDATE = 2,
> @.DELETE = 3,
> @.SELECT = 4,
> @.REPORT = 5
> /*
> **=========================================> ** BEGIN PROCESS
> **=========================================> */
> /*
> ** Cursor declare for inserted rows
> */
> DECLARE TrackerItem011_Cursor SCROLL CURSOR
> FOR SELECT TKI.SERIALLOG_VAL0,
> TKI.PRODUCTLOG_VAL0,
> TKI.REGIONLOG_VAL0,
> TKI.LOCATIONLOG_VAL0,
> TKI.REFERENCELOG_VAL0,
> TKI.timestamp
> FROM TRACKERITEM011 TKI
> WHERE ISNULL(TKI.InTracker, 0) = 0
> AND TKI.SERIALLOG_VAL0 IS NOT NULL
> AND EXISTS(SELECT 1
> FROM Inserted INS
> WHERE INS.timeStamp = TKI.timeStamp
> AND INS.project = TKI.project
> )
> FOR UPDATE OF TKI.InTracker
> /*
> ** Open cursor
> */
> OPEN TrackerItem011_Cursor
> /*
> ** First record
> */
> FETCH NEXT FROM TrackerItem011_Cursor
> INTO @.SerialLog,
> @.ProductLog,
> @.RegionLog,
> @.LocationLog,
> @.Reference1,
> @.TimeStampLog
> /*
> ** Loop over cursor
> */
> WHILE @.@.FETCH_STATUS = 0
> BEGIN
> /*
> ** Generate Tracker Item
> */
> EXECUTE spFisXSetTrackerItem @.SerialLog, @.ProductLog, @.RegionLog,
> @.LocationLog, @.TimeStampLog, @.Reference1, NULL, NULL, 0
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> /* Check for error */
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> IF @.@.ERROR <> 0
> BEGIN
> SELECT @.errno = 80001,
> @.errmsg = "Transaction Fault into 'TRACKERITEM011' table
> while update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') +
"'
> Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
> ISNULL(@.RegionLog, 'NULL') + "'."
> GOTO errHandler
> END
> /*
> ** Update this record
> */
> UPDATE TRACKERITEM011
> SET InTracker = 1
> WHERE CURRENT OF TrackerItem011_Cursor
> /*
> ** Next record
> */
> FETCH NEXT FROM TrackerItem011_Cursor
> INTO @.SerialLog,
> @.ProductLog,
> @.RegionLog,
> @.LocationLog,
> @.Reference1,
> @.TimeStampLog
> END
> /*
> ** Destroy cursor
> */
> CLOSE TrackerItem011_Cursor
> DEALLOCATE TrackerItem011_Cursor
>
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> /* Check for error */
> /*::::::::::::::::::::::::::::::::::::::::::::*/
> IF @.@.ERROR <> 0
> BEGIN
> SELECT @.errno = 80001,
> @.errmsg = "Transaction Fault into 'TRACKERITEM011' table
while
> update tracker information. Serial='" + ISNULL(@.SerialLog, 'NULL') + "'
> Reference='" + ISNULL(@.ProductLog, 'NULL') + "' Region='" +
> ISNULL(@.RegionLog, 'NULL') + "' Location='" + ISNULL(@.LocationLog, 'NULL')
+
> "'."
> GOTO errHandler
> END
> /*
> ** Exit point
> */
> ExitPoint:
> SET NOCOUNT OFF
> RETURN
> /*
> ** Handle Error
> */
> errHandler:
> EXEC master.dbo.xp_logevent @.errno, @.errmsg, informational
> RAISERROR @.errno @.errmsg
> ROLLBACK TRANSACTION
> GOTO ExitPoint
>
> "David Gugick" wrote:
> > Ton wrote:
> > > Hi All, I have a problem when I try to use a Cursor for update inside
> > > a trigger, the problem is that when I try to update another table
> > > using the values for temporary tables "inserted" or "deleted" appers
> > > this error: "For update cannot be specified on a read only cursor.
> > > Error 16957. Severity 16"
> > >
> > > I hope some one can help me
> >
> > Post your code please.
> >
> > --
> > David Gugick
> > Imceda Software
> > www.imceda.com
> >

Thursday, March 22, 2012

cursor + rounding?

Hi Guys,

I've created a cursor inside a function. When I break it down and execute the code piece by piece, no problem. However, try and parse it together and I get an error - 'Mixing old and new syntax is not allowed?' Something to do with the return statements? as I can alter the function to a procedure and it parses fine. Anyone come across this before?

Also, the values are being rounded when putting them into the cursor, even though I've declared the variables the cursor uses specifically as decimal? How can I get around this please?

Cheers,

Michelle

Michelle:

Can you describe what you are doing? This sounds rather vague.

|||

Blast, it didn't post. Umm, I've sorted the first problem, and I think I may have the answer to the second one. Will give it a go and let you know. Thanks for your help!

Cheers,

Michelle

|||

OK, both of those problems fixed. Should have been

DECLARE product_cursor CURSOR local SCROLL

NOT

DECLARE product_cursor SCROLL CURSOR

and Should have been:

decimal(8,2)

NOT

decimal.

Stupid mistakes! However, now I'm able to parse it fine, but am getting:

Msg 443, Level 16, State 15, Procedure CalculateFreight, Line 15

Invalid use of side-effecting or time-dependent operator in 'SELECT INTO' within a function.

Msg 443, Level 16, State 15, Procedure CalculateFreight, Line 25

Invalid use of side-effecting or time-dependent operator in 'UPDATE' within a function.

when I execute it!?

The SELECT INTO and UPDATE statements are fine when executed alone

Michelle

sql

Cursor - Structure of.

I wanted to know the internal workings of a 'cursor'.
What happens inside SQL Server from the time that it is declared, opened,
when it is used and finally closed and deallocated?
Have searched the web - but apart from examples and the pros/cons of using
them - have not come across the information that I want.
Can someone please provide this info to me or direct me to a site that has
this info?
Cheers!
SQLCatz.
I assume you are talking about Server side cursors?
This article might help you:
http://www.perftuning.com/_whitepape...ql_Cursors.pdf
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
>I wanted to know the internal workings of a 'cursor'.
> What happens inside SQL Server from the time that it is declared, opened,
> when it is used and finally closed and deallocated?
> Have searched the web - but apart from examples and the pros/cons of using
> them - have not come across the information that I want.
> Can someone please provide this info to me or direct me to a site that has
> this info?
> Cheers!
> SQLCatz.
|||Wei Xiao,
Thank you for the quick response!
But, this is not what I want.
MSSql_Cursors.pdf ~ There is much more information like this available on
SQL BOL. I want the internals.
Cheers!
SQLCatz.
"wei xiao [MSFT]" wrote:

> I assume you are talking about Server side cursors?
> This article might help you:
> http://www.perftuning.com/_whitepape...ql_Cursors.pdf
>
> --
> Wei Xiao [MSFT]
> SQL Server Storage Engine Development
> http://blogs.msdn.com/weix
>
> This posting is provided "AS IS" with no warranties, and confers no rights.
> "SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
> news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
>
>
|||what specifically do you want to know?
It depends on the cursor type:
Declare cursor is just metadata operation.
static cursor is the most costly at open time, because the whole result is
generated during open. (async population makes it somewhat less a problem).
keyset requires population of the keys, so it is less expesive at open time.
Dynamic is even less expensive at oepn time, but more expensive at fetch
time. Not all cursor can be dynamic. it depends on the query.
--
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:C634525C-5C5B-473A-B41A-CE4D7D22849C@.microsoft.com...[vbcol=seagreen]
> Wei Xiao,
> Thank you for the quick response!
> But, this is not what I want.
> MSSql_Cursors.pdf ~ There is much more information like this available on
> SQL BOL. I want the internals.
> Cheers!
> SQLCatz.
> "wei xiao [MSFT]" wrote:
rights.[vbcol=seagreen]
opened,[vbcol=seagreen]
using[vbcol=seagreen]
has[vbcol=seagreen]

Cursor - Structure of.

I wanted to know the internal workings of a 'cursor'.
What happens inside SQL Server from the time that it is declared, opened,
when it is used and finally closed and deallocated?
Have searched the web - but apart from examples and the pros/cons of using
them - have not come across the information that I want.
Can someone please provide this info to me or direct me to a site that has
this info?
Cheers!
SQLCatz.I assume you are talking about Server side cursors?
This article might help you:
http://www.perftuning.com/_whitepap...Sql_Cursors.pdf
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
>I wanted to know the internal workings of a 'cursor'.
> What happens inside SQL Server from the time that it is declared, opened,
> when it is used and finally closed and deallocated?
> Have searched the web - but apart from examples and the pros/cons of using
> them - have not come across the information that I want.
> Can someone please provide this info to me or direct me to a site that has
> this info?
> Cheers!
> SQLCatz.|||Wei Xiao,
Thank you for the quick response!
But, this is not what I want.
MSSql_Cursors.pdf ~ There is much more information like this available on
SQL BOL. I want the internals.
Cheers!
SQLCatz.
"wei xiao [MSFT]" wrote:

> I assume you are talking about Server side cursors?
> This article might help you:
> http://www.perftuning.com/_whitepap...Sql_Cursors.pdf
>
> --
> Wei Xiao [MSFT]
> SQL Server Storage Engine Development
> http://blogs.msdn.com/weix
>
> This posting is provided "AS IS" with no warranties, and confers no rights
.
> "SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
> news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
>
>|||what specifically do you want to know?
It depends on the cursor type:
Declare cursor is just metadata operation.
static cursor is the most costly at open time, because the whole result is
generated during open. (async population makes it somewhat less a problem).
keyset requires population of the keys, so it is less expesive at open time.
Dynamic is even less expensive at oepn time, but more expensive at fetch
time. Not all cursor can be dynamic. it depends on the query.
--
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:C634525C-5C5B-473A-B41A-CE4D7D22849C@.microsoft.com...[vbcol=seagreen]
> Wei Xiao,
> Thank you for the quick response!
> But, this is not what I want.
> MSSql_Cursors.pdf ~ There is much more information like this available on
> SQL BOL. I want the internals.
> Cheers!
> SQLCatz.
> "wei xiao [MSFT]" wrote:
>
rights.[vbcol=seagreen]
opened,[vbcol=seagreen]
using[vbcol=seagreen]
has[vbcol=seagreen]

Cursor - Structure of.

I wanted to know the internal workings of a 'cursor'.
What happens inside SQL Server from the time that it is declared, opened,
when it is used and finally closed and deallocated?
Have searched the web - but apart from examples and the pros/cons of using
them - have not come across the information that I want.
Can someone please provide this info to me or direct me to a site that has
this info?
Cheers!
SQLCatz.I assume you are talking about Server side cursors?
This article might help you:
http://www.perftuning.com/_whitepapers/MSSql_Cursors.pdf
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
>I wanted to know the internal workings of a 'cursor'.
> What happens inside SQL Server from the time that it is declared, opened,
> when it is used and finally closed and deallocated?
> Have searched the web - but apart from examples and the pros/cons of using
> them - have not come across the information that I want.
> Can someone please provide this info to me or direct me to a site that has
> this info?
> Cheers!
> SQLCatz.|||Wei Xiao,
Thank you for the quick response!
But, this is not what I want.
MSSql_Cursors.pdf ~ There is much more information like this available on
SQL BOL. I want the internals.
Cheers!
SQLCatz.
"wei xiao [MSFT]" wrote:
> I assume you are talking about Server side cursors?
> This article might help you:
> http://www.perftuning.com/_whitepapers/MSSql_Cursors.pdf
>
> --
> Wei Xiao [MSFT]
> SQL Server Storage Engine Development
> http://blogs.msdn.com/weix
>
> This posting is provided "AS IS" with no warranties, and confers no rights.
> "SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
> news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
> >I wanted to know the internal workings of a 'cursor'.
> > What happens inside SQL Server from the time that it is declared, opened,
> > when it is used and finally closed and deallocated?
> > Have searched the web - but apart from examples and the pros/cons of using
> > them - have not come across the information that I want.
> > Can someone please provide this info to me or direct me to a site that has
> > this info?
> > Cheers!
> > SQLCatz.
>
>|||what specifically do you want to know?
It depends on the cursor type:
Declare cursor is just metadata operation.
static cursor is the most costly at open time, because the whole result is
generated during open. (async population makes it somewhat less a problem).
keyset requires population of the keys, so it is less expesive at open time.
Dynamic is even less expensive at oepn time, but more expensive at fetch
time. Not all cursor can be dynamic. it depends on the query.
--
--
Wei Xiao [MSFT]
SQL Server Storage Engine Development
http://blogs.msdn.com/weix
This posting is provided "AS IS" with no warranties, and confers no rights.
"SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
news:C634525C-5C5B-473A-B41A-CE4D7D22849C@.microsoft.com...
> Wei Xiao,
> Thank you for the quick response!
> But, this is not what I want.
> MSSql_Cursors.pdf ~ There is much more information like this available on
> SQL BOL. I want the internals.
> Cheers!
> SQLCatz.
> "wei xiao [MSFT]" wrote:
> > I assume you are talking about Server side cursors?
> >
> > This article might help you:
> >
> > http://www.perftuning.com/_whitepapers/MSSql_Cursors.pdf
> >
> >
> > --
> > Wei Xiao [MSFT]
> > SQL Server Storage Engine Development
> > http://blogs.msdn.com/weix
> >
> >
> > This posting is provided "AS IS" with no warranties, and confers no
rights.
> >
> > "SQLCatz" <SQLCatz@.discussions.microsoft.com> wrote in message
> > news:E6AAEB16-3DB5-422C-A106-0D7E49F24397@.microsoft.com...
> > >I wanted to know the internal workings of a 'cursor'.
> > > What happens inside SQL Server from the time that it is declared,
opened,
> > > when it is used and finally closed and deallocated?
> > > Have searched the web - but apart from examples and the pros/cons of
using
> > > them - have not come across the information that I want.
> > > Can someone please provide this info to me or direct me to a site that
has
> > > this info?
> > > Cheers!
> > > SQLCatz.
> >
> >
> >

Monday, March 19, 2012

Currency or Double preferred?

I'm wondering whether it's better to choose Currency or Double for measure datatypes if the aggregated values will fit inside either datatype. Thoughts? Which would be smaller in terms of storage? If the number gets real big will either Currency or Double lose precision? Are rounding errors more prevalent with one rather than the other?

I have read the following pages but can't seem to make heads or tails of it in terms of best practices:

http://msdn2.microsoft.com/en-us/library/ms129408.aspx

http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbtype.aspx

http://msdn2.microsoft.com/en-us/library/678hzkk9(VS.80).aspx

http://msdn2.microsoft.com/en-us/library/364x0z75(VS.80).aspx

There is no Double in SQL Server so you have to use either Currency or Decimal or you may have to do conversion before sending the value to SQL Server. Try the link below for the SQL Server Types, ADO.NET types and .NET types. Hope this helps.

http://msdn2.microsoft.com/en-us/library/ms131092.aspx

|||

Caddre, thanks for the reply. That was a good link if you're doing SQLCLR stuff.

The Double SSAS datatype is equivalent to the float datatype in SQL Server. The Currency SSAS datatype is equivalent to the money datatype in SQL Server. Regardless, I'm not interested in SQL Server datatypes, just Analysis Services.

The question still remains, which datatype do you choose in SSAS if either will work: Currency or Double?

|||

Float is not a data type for persistence in any layer of SQL Server because of known precision issues in all programming languages. And my reply was related to your posted links which are clr related.

|||

Hi Furmangg,

If you have to store financial information in your cube and your database stores it as money(currency) you should definitely use currency data type for your mesures. Operations with the currency data type take less CPU power (no FPU calculations) and moreover will be better comressed by the storage engine.

Also if your information could be stored in currency data type (from -922,337,203,685,477.5808 to 922,337,203,685,477.5807) you schould take this type for your measures.

Best regards,

Vladimir Chtepa

|||

Thanks Vladimir. That's the answer I was looking for. I appreciate it.