Showing posts with label rowcount. Show all posts
Showing posts with label rowcount. Show all posts

Thursday, February 9, 2012

@@ROWCOUNT Support?

I am trying to work a statement like the below - but am getting an error - I assume that @.@.ROWCOUNT is not supported?

UPDATE MobileInvoiceImport SET OrderDetailID = '123', QuantityReceived = '66' WHERE OrderDetailID = '123'

IF @.@.ROWCOUNT = 0

INSERT INTO MobileInvoiceImport (OrderDetailID, QuantityReceived) VALUES('123','1')

there is no support for @.@.ROWCOUNT but when you ExecuteNonQuery() on your insert command, the return value is the number of rows affected. you cannot batch together successive statements with SQL Mobile, so using this value in managed code is going to have to be your conditional value anyway.

Darren

@@RowCount problem

Hi I'm opening a RecordSet using the following code :

declare tcrl cursor FAST_FORWARD for SELECT TSample.ISmpCode
FROM TCertResults TSample
WHERE (TSample.ISmpShortCode ='24/12359')

Open trcl

What I want to be able to get a count of this recordset. Been thru the TSQL help and it's pointing me toward the @.@.RowCount command but I can't seem to get this working.

Any help would be apprieciated@.@.ROWCOUNT returns the number of rows affected by the last statement. Use the @.@.CURSOR_ROWS function to receive the number of qualifying rows in the last opened cursor.

BTW - do you really need cursor? It heavily hits DB performance.|||I agree,

Wont SELECT COUNT(*) FROM TCertResults TSample
WHERE TSample.ISmpShortCode ='24/12359' do the trick?|||No cursrors...No cursors...

There is precious little you can do without them...

Describe what your trying to do...|||The cursor is a lot more complicated than posted but the basic gist is that the results of the cursor will be 'fetched' into variables which will then be used to update other tables, etc. Then the variables will be repopulated using the fetch next command. When updating the other tables with the results of the original cursor, one of the values that I need to write is total amount of records from the original cursor.
So I need the recordcount as soon as the cursor is open. But as I'm sure you've gathered I haven't got a clue how to get this!|||Makes no sense to me...(being sober sucks...)

So you want to write the count of the entire result set, for every row in the cursor?

That seems to be a derivation of a thing...

Anyway...do this before you open the cursor and just use the local variable..

DECLARE @.x int
SELECT @.x=COUNT(*)
FROM TCertResults TSample
WHERE ISmpShortCode ='24/12359'

Still, you could do all of this without a cursor.

Good luck|||Looks for me you can use temp tables instead of cursors...

But if you are decided to stay with them - didn't the @.@.CURSOR_ROWS suits you? Why - any reason? error? sth other?|||Using the Cursor_Row function always gave me a answer of -1. To be fair though I'm new to TSQL so my syntax could be totally wrong. And to prove it here's my syntax

declare tcrl cursor FAST_FORWARD for SELECT dbo.TSample.ISmpCode
FROM dbo.TSample INNER JOIN
dbo.TCertResults ON dbo.TSample.ISmpN = dbo.TCertResults.ISmpN
WHERE (dbo.TSample.ISmpShortCode = '24/12359')

Open tcrl

PRINT @.@.CURSOR_ROWS|||You don't my count solution?|||Your solution works great thank you.
I was just continuing the thread in the hope that someone could tell me what the correct syntax @.@.Cursor_Rows function was.

Cheers|||Look in BOL (Books Online):

@.@.CURSOR_ROWS
Returns the number of qualifying rows currently in the last cursor opened on the connection. To improve performance, Microsoft SQL Server can populate large keyset and static cursors asynchronously. @.@.CURSOR_ROWS can be called to determine that the number of the rows that qualify for a cursor are retrieved at the time @.@.CURSOR_ROWS is called.

Return value Description
-m The cursor is populated asynchronously. The value returned (-m) is the number of rows currently in the keyset.
-1 The cursor is dynamic. Because dynamic cursors reflect all changes, the number of rows that qualify for the cursor is constantly changing. It can never be definitely stated that all qualified rows have been retrieved.
0 No cursors have been opened, no rows qualified for the last opened cursor, or the last-opened cursor is closed or deallocated.
n The cursor is fully populated. The value returned (n) is the total number of rows in the cursor.

Don't use Cursors...|||Originally posted by SexualChocolate
Using the Cursor_Row function always gave me a answer of -1. To be fair though I'm new to TSQL so my syntax could be totally wrong. And to prove it here's my syntax

declare tcrl cursor FAST_FORWARD for SELECT dbo.TSample.ISmpCode
FROM dbo.TSample INNER JOIN
dbo.TCertResults ON dbo.TSample.ISmpN = dbo.TCertResults.ISmpN
WHERE (dbo.TSample.ISmpShortCode = '24/12359')

Open tcrl

PRINT @.@.CURSOR_ROWS

The Great Holy Online Book says:
"If you receive '-1' as return from @.@.CURSOR_ROWS that it means:
The cursor is dynamic. Because dynamic cursors reflect all changes, the number of rows that qualify for the cursor is constantly changing. It can never be definitely stated that all qualified rows have been retrieved. You can try with Brett Kaiser's count solution. So says The Great Holy Online Book"

Again:
<ghost_voice>Beware of cursors... uuuuaahahahahahaaa....</ghost_voice>|||like I say I'm fairly new to all this. I'm using a cursor because I don't know of another was to open a recordset and step thru it. If there is an alternative then please point me at it|||Count - to determine no of records,
temp tables or derived tables to help recordset operations.|||People that normally write code in client tools tend to use cursors when writing code in SQLServer..thats perfectly understood since thats the way its done in vb, c, c# etc.

BUT SqlServer is about batch updates (most of the time); lots and lots and lots of rows being updated/inserted/deleted at once, a cursor just isnt efficient enough..

My role is:If you are forced to use cursors or other types of loops in more than 1% of your sql code you have problaly done something wrong..|||Fair enough. So is there another way you can open a RecordSet populate variables based upon the first row returned from the recordset, perform an update on another table based upon the values held within these variables, step to the next row, repopulate the variables, perform the update again, etc. Without using a cursor?

Everybody tells me that there evil and everything I've read instructs me not to use them but is there another way?

TSQL novice|||You need to get your mindset away from "stepping to the next row", and think about updating ALL the rows SIMULTANEOUSLY. That is what set-based transactions are all about, and that is the power of a database management engine.

If you want to know how to do it, you will first need to read the Books Online entries for SELECT statements and UPDATE statements. Then, if you are still confused, post again and give more details about what you are trying to do. We can assist you in writing the code, but we need a base to build upon.|||Can you give us an example of an update and the cursor itself...also, tying the # of records to the "batch" that result set came from is sort of meangless...because data is fluid by nature , that number is wrong the instant you set it on the row...

Maybe a brief business description of what's going will help make things more clear to us.|||Okey dokey, heres the cursor:

declare tcrl cursor FAST_FORWARD for SELECT TSample.ISmpCode, TAnalyses.IAnalysesN, TSample.ISmpShortCode, TCertResults.ICertResultsN, TCertResults.LabNo,
TCertResults.LabNoDateTime, TJob.IJobCode, TAnalyses.IAnCode, TAnalyses.TemperatureID + 48 AS MyTempAscii,
TMedia.SpreadOrPour, TAnalyses.MediaID + 48 AS MyMediaAscii, TAnalyses.IAnShortCertDesc, TCertResultSpecDilution.Dilution,
TCertResultSpecDilution.SpecDilN, TAnalyses.KiestraTest, TAnalyses.LabelRule, TAnalyses.IAnWorkType, TAnalyses.Pathogen,
TAnalyses.TemperatureID,TAnalyses.CameraSortID,TAn alysesIncubation.IncubationLength,TAnalysesIncubat ionTolerance.IncubationTolerance
FROM TCertResults INNER JOIN
TSample ON TCertResults.ISmpN = TSample.ISmpN INNER JOIN
TJob ON TSample.IJobN = TJob.IJobN INNER JOIN
TAnalyses ON TCertResults.IAnalysesN = TAnalyses.IAnalysesN INNER JOIN
TCertResultSpecDilution ON TCertResults.ICertResultsN = TCertResultSpecDilution.ICertResultsN INNER JOIN
TAnalysesIncubationTolerance ON
TAnalyses.IncubationToleranceID = TAnalysesIncubationTolerance.IncubationToleranceID LEFT OUTER JOIN
TMedia ON TAnalyses.MediaID = TMedia.MediaID LEFT OUTER JOIN
TAnalysesIncubation ON TAnalyses.IncubationID = TAnalysesIncubation.IncubationID
WHERE (TSample.ISmpShortCode IN (SELECT * FROM dbo.udf_Txt_SplitTAB(@.MYLSN,','))) AND (TCertResults.LabNo IS NOT NULL) AND (TCertResults.LabNoDateTime IS NOT NULL) AND
(TAnalyses.KiestraTest = 1) AND (TAnalyses.LabelRule = 'Shared') AND (TAnalyses.IAnWorkType = 'M') AND
(TAnalyses.Pathogen = 0)

Open tcrl
Fetch tcrl into @.MyLongLsn,@.MyAnalysisID,@.MyShortCode,@.MyCertResul tsN,@.MyLabNo,@.MyLabNoDateTime,@.MyJobCode,@.MyIanCod e,@.MyTempAscii,@.MySpreadOrPour,@.MyMediaAscii,@.MySh ortTestDesc,@.MyDilution,@.MySpecDilN,@.MyKiestraTest ,@.MyLabelRule,@.MyIanWorkType,@.MyPathogen,@.MyTemper atureID,@.MyCameraSortID,@.MyIncubationLength,@.MyInc ubationTolerance
While @.@.Fetch_status=0

Based upon the results of the this cursor variables will be populated and tested for certain criteria and other variables populated as a result of the results. Something like:

IF @.MySpreadOrPour = 'Pour'
BEGIN
Set @.MyMediaID = '0'
END
ELSE
BEGIN
Set @.myMediaID = @.MyMediaAscii - 48
END

Then finally another table will be populated with the values held within the variables:

INSERT INTO TBarCodAFile ( Field1, Field2, Field3, Field4, Field5, Field6, Field7, Field8, Field9, Field10, Field11, Dilution, LabelRule, DateDue)
VALUES (@.MyBarCode,@.MyLongLSN,@.MyJobCode,@.MyShortTestDesc ,@.MyDatePlateToBeRead,@.MyMediaID,@.MyStacker,@.MyWhi teLabels,@.MyAnalystPosition,@.MyEmpID,@.MyFormatting ,@.MyDilution,@.MyLabelRule,@.MyWholeDatePlateToBeRea d).

I'll then move to the next record in the recordset (Fetch next from tcrl into @.MyLongLsn,@.MyAnalysisID,@.MyShortCode,@.MyCertResul tsN,@.MyLabNo,@.MyLabNoDateTime,@.MyJobCode,@.MyIanCod e,@.MyTempAscii,@.MySpreadOrPour,@.MyMediaAscii,@.MySh ortTestDesc,@.MyDilution,@.MySpecDilN,@.MyKiestraTest ,@.MyLabelRule,@.MyIanWorkType,@.MyPathogen,@.MyTemper atureID,@.MyCameraSortID,@.MyIncubationLength,@.MyInc ubationTolerance).

Then do all my tests again and perform the INSERT statement again. And continue unless the end of the recordset.

No doubt this is a serious pain in the arse but I can find no other way of doing it.|||FIRST...lose the fully qualified table names...

Second, THAT'S ONE HELL OF A JOIN...ARE THE KEYS ALL IDENTITY?

Third, if it takes a long time to run, you could save the results to a temp table and do all of your work as a join to that

Fourth (and I'm liking the temp table thing more and more0 you could do the insert like:

INSERT INTO TBarCodAFile(
Field1
, Field2
, Field3
, Field4
, Field5
, Field6
, Field7
, Field8
, Field9
, Field10
, Field11
, Dilution
, LabelRule
, DateDue)
SELECT b.ISmpCode
, d.IAnalysesN
, b.ISmpShortCode
, a.ICertResultsN
, a.LabNo
, a.LabNoDateTime
, c.IJobCode
, d.IAnCode
, d.TemperatureID + 48 AS MyTempAscii
, g.SpreadOrPour
, d.MediaID + 48 AS MyMediaAscii
, d.IAnShortCertDesc
, e.Dilution
, e.SpecDilN
, d.KiestraTest
, d.LabelRule
, d.IAnWorkType
, d.Pathogen
, d.TemperatureID
, d.CameraSortID
, h.IncubationLength
, f.IncubationTolerance
FROM TCertResults a
INNER JOIN TSample b
ON a.ISmpN = b.ISmpN
INNER JOIN TJob c
ON b.IJobN = c.IJobN
INNER JOIN TAnalyses d
ON a.IAnalysesN = d.IAnalysesN
INNER JOIN TCertResultSpecDilution e
ON a.ICertResultsN = e.ICertResultsN
INNER JOIN TAnalysesIncubationTolerance f
ON d.IncubationToleranceID = f.IncubationToleranceID
LEFT JOIN TMedia g
ON d.MediaID = g.MediaID
LEFT JOIN TAnalysesIncubation h
ON d.IncubationID = h.IncubationID
WHERE (TSample.ISmpShortCode IN
(SELECT *
FROM dbo.udf_Txt_SplitTAB(@.MYLSN,',')
)
)
AND (TCertResults.LabNo IS NOT NULL)
AND (TCertResults.LabNoDateTime IS NOT NULL)
AND (TAnalyses.KiestraTest = 1)
AND (TAnalyses.LabelRule = 'Shared')
AND (TAnalyses.IAnWorkType = 'M')
AND (TAnalyses.Pathogen = 0)|||Obviously the columns do not match...there's more in the select than the INSERT, you need to match them up...

How long does that monster take to run as a stand alone select?|||I've got to be honest and at this point say you've lost me. Maybe I just can't get my head around this temp table idea but as I see it if I populated a temp table with the results of a straight select statement surely I'd then have to read all the rows from this table to perform the criteria testing and wouldn't I still a cursor to do this. Or more likely I'm being a cretin.

Most of the linking fields are identity,yes.

Oh yeah its a proper beast, it used to be coded in Access VBA and it could take up to ten minutes to complete depending on the amount of rows affected.

I've been asked to re-code it server side and its the first time I've ventured into server side programming, so please excuse my naivety.|||Where did I lose you?

The INSERT?

The Table Aliases?

The Temp Table?

I would do...

SELECT b.ISmpCode
, d.IAnalysesN
, b.ISmpShortCode
, a.ICertResultsN
, a.LabNo
, a.LabNoDateTime
, c.IJobCode
, d.IAnCode
, d.TemperatureID + 48 AS MyTempAscii
, g.SpreadOrPour
, d.MediaID + 48 AS MyMediaAscii
, d.IAnShortCertDesc
, e.Dilution
, e.SpecDilN
, d.KiestraTest
, d.LabelRule
, d.IAnWorkType
, d.Pathogen
, d.TemperatureID
, d.CameraSortID
, h.IncubationLength
, f.IncubationTolerance
INTO WorkTable
FROM TCertResults a
INNER JOIN TSample b
ON a.ISmpN = b.ISmpN
INNER JOIN TJob c
ON b.IJobN = c.IJobN
INNER JOIN TAnalyses d
ON a.IAnalysesN = d.IAnalysesN
INNER JOIN TCertResultSpecDilution e
ON a.ICertResultsN = e.ICertResultsN
INNER JOIN TAnalysesIncubationTolerance f
ON d.IncubationToleranceID = f.IncubationToleranceID
LEFT JOIN TMedia g
ON d.MediaID = g.MediaID
LEFT JOIN TAnalysesIncubation h
ON d.IncubationID = h.IncubationID
WHERE (TSample.ISmpShortCode IN
(SELECT *
FROM dbo.udf_Txt_SplitTAB(@.MYLSN,',')
)
)
AND (TCertResults.LabNo IS NOT NULL)
AND (TCertResults.LabNoDateTime IS NOT NULL)
AND (TAnalyses.KiestraTest = 1)
AND (TAnalyses.LabelRule = 'Shared')
AND (TAnalyses.IAnWorkType = 'M')
AND (TAnalyses.Pathogen = 0)

INSERT INTO TBarCodAFile(
Field1
, Field2
, Field3
, Field4
, Field5
, Field6
, Field7
, Field8
, Field9
, Field10
, Field11
, Dilution
, LabelRule
, DateDue)
SELECT ColList
FROM WorkTable

DROP WorkTable|||This is not all that bad. This should get you started:

INSERT INTO TBarCodAFile
(--Field1,
Field2,
Field3,
Field4,
--Field5,
Field6,
--Field7,
--Field8,
--Field9,
--Field10,
--Field11,
Dilution,
LabelRule
--DateDue
)
select --MyBarCode function,
TSample.ISmpCode,
TJob.IJobCode,
TAnalyses.IAnShortCertDesc,
--MyDatePlateToBeRead function
Case when TMedia.SpreadOrPour = 'Pour' then 0 else TAnalyses.MediaID end,
--MyStacker function,
--MyWhiteLabels function,
--MyAnalystPosition function,
--MyEmpID function,
--MyFormatting function,
TCertResultSpecDilution.Dilution,
TAnalyses.LabelRule
--MyWholeDatePlateToBeRead function
FROM TCertResults
INNER JOIN TSample ON TCertResults.ISmpN = TSample.ISmpN
INNER JOIN TJob ON TSample.IJobN = TJob.IJobN
INNER JOIN TAnalyses ON TCertResults.IAnalysesN = TAnalyses.IAnalysesN
INNER JOIN TCertResultSpecDilution ON TCertResults.ICertResultsN = TCertResultSpecDilution.ICertResultsN
INNER JOIN TAnalysesIncubationTolerance ON TAnalyses.IncubationToleranceID = TAnalysesIncubationTolerance.IncubationToleranceID
LEFT OUTER JOIN TMedia ON TAnalyses.MediaID = TMedia.MediaID
LEFT OUTER JOIN TAnalysesIncubation ON TAnalyses.IncubationID = TAnalysesIncubation.IncubationID
WHERE TSample.ISmpShortCode IN (SELECT * FROM dbo.udf_Txt_SplitTAB(@.MYLSN,',')) --This should be changed to a join...
AND TCertResults.LabNo IS NOT NULL
AND TCertResults.LabNoDateTime IS NOT NULL
AND TAnalyses.KiestraTest = 1
AND TAnalyses.LabelRule = 'Shared'
AND TAnalyses.IAnWorkType = 'M'
AND TAnalyses.Pathogen = 0

I've commented out elements where the calculation function was not available. It should run MUCH faster if you convert it to this format.

...and I like using qualified column names, Brett! To each his own...|||Yeah to each his/her own...

But it's so verbose...

Sounds like they need to do many actions against many different tables based on the result.

What do you think of the temp table idea?

Just 1 pass versus over and over...|||Temp table (or table variable) is better than a cursor, no doubt.|||Ok I'll give those idea's a blast. Doubtless I'll be back in touch in about 15 minutes!!

Thanks again for your time and patience|||Originally posted by SexualChocolate
Ok I'll give those idea's a blast. Doubtless I'll be back in touch in about 15 minutes!!

Thanks again for your time and patience

OK...I gotta know...2:44?

Where in the world are you?|||Birmingham, England

How do I call a function from within a select statement? Told you I'd be back!|||You're better off starting a new thread for a new question but...

SELECT dbo.udf_myFunction99(Col1)....|||Thanks to everyone who posted.

Ta

@@RowCount output param

The following stored procedure sets a value for the @.@.RowCount global variable.

How do I make use of it in the Data Access Layer?

When I set the SPROC as the source for the object, the value numberRows does not appear to be an option. In the end I just want to set the value of @.@.RowCount to a Label.Text

What should I do?

ALTER PROCEDURE dbo.ap_Select_ModelRequests_RequestDateTime@.selectDatedatetime ,@.selectCountryInt ASSELECT DISTINCT confignameFROM ModelRequestsJOIN CC_host.dbo.usr_cmcAs t2ON t2.user_id = ModelRequests.usernameJOIN CountriesONCountries.Country_Short = t2.countryWHERE RequestDateTime >= @.selectDateand RequestDateTime <dateadd(dd,1, @.selectDate)AND configname <>''AND interfacenameLIKE'%DOWNLOAD%'AND result = 0AND Country_ID = @.selectCountryORDER BY confignameSELECT@.@.RowCountAs numberRowsGO

try this:

declare @.MyRowCounter int
select @.MyRowCounter = @.@.RowCount as numberRows

|||

This will work as written, but what you get back is an answer set with 1 row and 1 column, you would use a datareader to read it.

A perhaps better -- or at least clearer -- way is to store the number in an output variable. Then, when you set up the call to execute the proc you declare the parameter direction as OUTPUT (this link has an example --http://www.msdner.com/forum/thread445973.html)

ALTER PROCEDURE dbo.ap_Select_ModelRequests_RequestDateTime
@.selectDatedatetime
,@.selectCountryInt

,@.numberRows int OUTPUT
AS

SELECT DISTINCT confignameFROM ModelRequestsJOIN
CC_host.dbo.usr_cmcAs t2ON
t2.user_id = ModelRequests.usernameJOIN
CountriesON
Countries.Country_Short = t2.country
WHERE RequestDateTime >= @.selectDateand RequestDateTime <dateadd(dd,1, @.selectDate)
AND configname <>''AND interfacenameLIKE'%DOWNLOAD%'AND result = 0AND Country_ID = @.selectCountry
ORDER BY configname
SELECT @.numberRows=@.@.rowcount

@@Rowcount or output parameters error

I have the following stored procedure working with an Access 2000 front end. The output parameters returned to Access are both Null when the record is successfully updated (ie when @.@.Rowcount = 1), but the correct parameters are returned when the update fails. I'm a bit new to using output parameters, but I have them working perfectly with an insert sproc, and they look basically the same. What bonehead error have I made here? The fact that the record is updated indicates to me that the Commit Trans line is being executed, so why aren't the 2 output parameters set?

TIA

EDIT: Solved, sort of. I found that dropping the "@.ResNum +" from "@.ResNum + ' Updated'" resolved the problem (@.ResNum is an input parameter). This implies that the variable lost its value between the SQL statement and the If/Then, since the SQL correctly updates only the appropriate record from the WHERE clause. Is this supposed to happen? I looked in BOL, and if it's addressed there I missed it.

CREATE PROCEDURE [procResUpdate]

Various input parameters here,

@.RetCode as int Output, @.RetResNum as nvarchar(15) Output

AS

Declare @.RowCounter int

Begin Tran

UPDATE tblReservations
SET Various set statements here, LastModified = @.LastModified + 1
WHERE ResNum = @.ResNum AND LastModified = @.LastModified

SELECT @.RowCounter = @.@.ROWCOUNT

If @.RowCounter = 1
Begin
Commit Tran
Select @.RetCode = 1
Select @.RetResNum = @.ResNum + ' Updated'
End
Else
Begin
Rollback Tran
Select @.RetCode = 0
Select @.RetResNum = 'Update Failed'
End
GOPost the complete DDL for the proc (including @.ResNum) and a sample of calling it that produces the problem you describe.

Regards,

hmscott|||Here's the complete sproc (I added back the offending part in red):

CREATE PROCEDURE [procResUpdate]

@.ReqDate as datetime, @.PassName as nvarchar(25), @.DispDate as datetime, @.PassPhone as nvarchar(25),
@.PassQuant as smallint, @.AuthBy as nvarchar(25), @.AcctID as smallint, @.PuLandmark as smallint, @.PuStreet as nvarchar(50),
@.PuCity as smallint, @.PuXStreet as nvarchar(50), @.PuPoint as nvarchar(50), @.DestLandmark as smallint, @.DestStreet as nvarchar(50),
@.DestCity as smallint, @.DestXStreet as nvarchar(50), @.DestPoint as nvarchar(50), @.Operator as smallint, @.Comments as nvarchar(250),
@.DriverReq as nvarchar(25), @.CarType as smallint, @.EstHours as money, @.EstPrice as money, @.CCType as nvarchar(25), @.CCnum as nvarchar(25),
@.CCAuthNum as nvarchar(25), @.CarQuant as tinyint, @.ResNum as int, @.Status as smallint, @.LastModified as tinyint,

@.RetCode as int = Null Output, @.RetResNum as nvarchar(15) = Null Output

AS

Declare @.RowCounter int

Begin Tran

UPDATE tblReservations
SET ReqDateTime = @.ReqDate, PassName = @.PassName, DispDateTime = @.DispDate, PassPhone = @.PassPhone, PassQuant = @.PassQuant, AuthBy = @.AuthBy, AcctID = @.AcctID,
PuLandmarkID = @.PuLandmark, PuStreet = @.PuStreet, PuCityID = @.PuCity, PuXStreet = @.PuXStreet, PuPoint = @.PuPoint, DestLandmarkID = @.DestLandmark, DestStreet = @.DestStreet,
DestCityID = @.DestCity, DestXStreet = @.DestXStreet, DestPoint = @.DestPoint, OperatorID = @.Operator, Comments = @.Comments, DriverReq = @.DriverReq, CarType = @.CarType,
EstHours = @.EstHours, EstPrice = @.EstPrice, CCType = @.CCType, CCNum = @.CCnum, CCAuthNum = @.CCAuthNum, CarQuant = @.CarQuant, Status = @.Status, LastModified = @.LastModified + 1
WHERE ResNum = @.ResNum AND LastModified = @.LastModified

SELECT @.RowCounter = @.@.ROWCOUNT

If @.RowCounter = 1
Begin
Commit Tran
Select @.RetCode = 1
Select @.RetResNum = ' Updated'
End
Else
Begin
Rollback Tran
Select @.RetCode = 0
Select @.RetResNum = @.ResNum + ' Update Failed'
End
GO


and the VBA that calls it. The 2 highlighted lines will be null if the "@.ResNum + " is included. Otherwise, it runs fine.

Public Sub cmdUpdate_Click()
Dim strSQL As String
Dim strField As String
Dim fOK As Integer
Dim intCount As Integer
Dim x As Integer
Dim strMsg As String
Dim cmd As ADODB.Command
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim tdf As DAO.TableDef
Dim dteReqDate As Date
Dim dteDispDate As Date

On Error GoTo ErrorHandler

dteReqDate = Me.txtReqDate & " " & Me.txtReqTime
dteDispDate = DateAdd("n", -Nz(Me.txtMinutesAhead, 0), dteReqDate)

Call EstablishConnection
Set db = CurrentDb()
Set cmd = New ADODB.Command
Set rst = New ADODB.Recordset
Set tdf = db.TableDefs("tblReservations_Local")
rst.ActiveConnection = objConn

With cmd
.ActiveConnection = objConn
.CommandText = "procResUpdate"
.CommandType = adCmdStoredProc

.Parameters.Append .CreateParameter("@.ReqDate", adDBTimeStamp, adParamInput, , dteReqDate)
.Parameters.Append .CreateParameter("@.PassName", adVarChar, adParamInput, 25, Me.txtPassName)
.Parameters.Append .CreateParameter("@.DispDate", adDBTimeStamp, adParamInput, , dteDispDate)
.Parameters.Append .CreateParameter("@.PassPhone", adVarChar, adParamInput, 25, Me.txtPassPhone)
.Parameters.Append .CreateParameter("@.PassQuant", adInteger, adParamInput, , Me.txtPassQuant)
.Parameters.Append .CreateParameter("@.AuthBy", adVarChar, adParamInput, 25, Me.txtAuthBy)
.Parameters.Append .CreateParameter("@.AcctID", adInteger, adParamInput, , Me.cboAcctNum)
.Parameters.Append .CreateParameter("@.PuLandmark", adInteger, adParamInput, , Me.cboLandmark)
.Parameters.Append .CreateParameter("@.PuStreet", adVarChar, adParamInput, 50, Me.txtPuAddress)
.Parameters.Append .CreateParameter("@.PuCity", adInteger, adParamInput, , Me.cboPuCity)
.Parameters.Append .CreateParameter("@.PuXStreet", adVarChar, adParamInput, 50, Me.txtPuXStreet)
.Parameters.Append .CreateParameter("@.PuPoint", adVarChar, adParamInput, 50, Me.txtPuPoint)
.Parameters.Append .CreateParameter("@.DestLandmark", adInteger, adParamInput, , Me.cboDestLandmark)
.Parameters.Append .CreateParameter("@.DestStreet", adVarChar, adParamInput, 50, Me.txtDestAddress)
.Parameters.Append .CreateParameter("@.DestCity", adInteger, adParamInput, , Me.cboDestCity)
.Parameters.Append .CreateParameter("@.DestXStreet", adVarChar, adParamInput, 50, Me.txtDestXStreet)
.Parameters.Append .CreateParameter("@.DestPoint", adVarChar, adParamInput, 50, Me.txtDestPoint)
.Parameters.Append .CreateParameter("@.Operator", adInteger, adParamInput, , Me.txtOperator)
.Parameters.Append .CreateParameter("@.Comments", adVarChar, adParamInput, 250, Me.txtComments)
.Parameters.Append .CreateParameter("@.DriverReq", adVarChar, adParamInput, 25, Me.txtDriverReq)
.Parameters.Append .CreateParameter("@.CarType", adInteger, adParamInput, , Me.cboCarType)
.Parameters.Append .CreateParameter("@.EstHours", adCurrency, adParamInput, , Me.txtEstHours)
.Parameters.Append .CreateParameter("@.EstPrice", adCurrency, adParamInput, , Me.txtEstPrice)
.Parameters.Append .CreateParameter("@.CCType", adVarChar, adParamInput, 25, Me.cboCCType)
.Parameters.Append .CreateParameter("@.CCnum", adVarChar, adParamInput, 25, Me.txtCCNum)
.Parameters.Append .CreateParameter("@.CCAuthNum", adVarChar, adParamInput, 25, Me.txtCCAuthNum)
.Parameters.Append .CreateParameter("@.CarQuant", adInteger, adParamInput, , Me.txtCarQuant)
.Parameters.Append .CreateParameter("@.ResNum", adInteger, adParamInput, , Me.txtResNum)
.Parameters.Append .CreateParameter("@.Status", adInteger, adParamInput, , Me.cboStatus)
.Parameters.Append .CreateParameter("@.LastModified", adInteger, adParamInput, , Me.txtLastModified)

.Parameters.Append .CreateParameter("@.RetCode", adInteger, adParamOutput)
.Parameters.Append .CreateParameter("@.RetResNum", adVarChar, adParamOutput, 15)

.Execute

End With

fOK = cmd.Parameters("@.RetCode")
strMsg = cmd.Parameters("@.RetResNum")|||Update for anyone interested. It seems that there was a type mismatch occurring. @.ResNum is a numeric value (data type int), and apparently in this line that caused a problem:

Select @.RetResNum = @.ResNum + ' Update Failed'

I assumed it would concatenate the two values. If I create a new varchar variable and populate it with the value of @.ResNum (converted to varchar) and use that, everything works fine. What threw me was that not only was that return parameter null, but the other one was too.

@@rowcount in SQL server 2000

Hi,

We have migrated a stored procedure from SQL 7 to SQL 2000 . We made some changes to remove the Set rowcount and replaced it by rowcount function. But @.@.ROWCOUNT does not return the correct value. It returns 0 when it should return 1.

Here is a section of the code:
DECLARE @.no_of_rows int
DECLARE @.curr_prnt_cmp_convert char(5)

SELECT @.local_cmps_loop = 1,
@.master_child_loop = 1,
@.acct_list_loop = 1,
@.master_child2_loop = 1,
@.no_of_rows = 0,
@.curr_prnt_cmp_convert = ' '

SET NOCOUNT ON

/* -- Temporary Tables Creation -- */

CREATE TABLE #local_cmps (cmp_int smallint, org_flg tinyint, pflg tinyint)

CREATE TABLE #master_child(bus_int smallint, prnt_cmp_int smallint, chld_cmp_int smallint, pflg tinyint)

CREATE TABLE #acct_list (bus_int smallint, prnt_cmp_int smallint, acct_int int)

/* -- Insert all Local Components -- */

INSERT INTO #local_cmps (cmp_int, org_flg, pflg)
(SELECT DISTINCT cmp_int, origin_flg, 0
FROM tbl_sd_components
WHERE origin_flg = 1)

/* -- Get Fiscal Year from Data Base -- */

SELECT @.fiscal_year=num_data
FROM tbl_sd_sys_control
WHERE sys_ctl_typ = 1

/* -- Start Buiding Tables for Local Components -- */

WHILE (@.local_cmps_loop = 1)
/* WHILE ((SELECT COUNT(*) FROM #local_cmps WHERE pflg = 0) > 0) */
BEGIN

/*LEAPMIGRA : Commented and added TOP 1 to subsequect SELECT ; set rowcount 1 */

/* -- Select the Unprocessed Parent Component -- */

SELECT TOP 1 @.curr_prnt_cmp = cmp_int
FROM #local_cmps
WHERE pflg = 0

SELECT @.no_of_rows = @.@.ROWCOUNT

IF (@.no_of_rows = 0)
BREAK /* WHILE (@.local_cmps_loop = 1)*/

The value of @.no_of_rows should be 1. It gives 0
Please advise.

Thanks and Regards,
Paritamaybe a simpler test is in order...

DECLARE @.no_of_rows int
set nocount on
select top 1 au_id,au_lname,phone,contract from pubs.dbo.authors
set @.no_of_rows = @.@.rowcount
select @.no_of_rows as '@.no_of_rows TOP 1'

select au_id,au_lname,phone,contract from pubs.dbo.authors
set @.no_of_rows = @.@.rowcount
select @.no_of_rows as '@.no_of_rows'

and more to your code...
declare @.no_of_rows int
declare @.Tbl table(au_id varchar (11), au_lname varchar (40), phone char (12), contract bit)

set nocount on

insert into @.Tbl
select au_id,au_lname,phone,contract from pubs.dbo.authors
set @.no_of_rows = @.@.rowcount
select @.no_of_rows as '@.no_of_rows inserted'

select top 1 * from @.Tbl
set @.no_of_rows = @.@.rowcount
select @.no_of_rows as '@.no_of_rows TOP 1'

select * from @.Tbl
set @.no_of_rows = @.@.rowcount
select @.no_of_rows as '@.no_of_rows'|||Hi Paul,
Thanks for your reply. I did test this procedure by executing some print commands after fetching @.@.rowcount.

I also executed a dummy procedure with @.@.ROWCOUNT and it worked. But the migrated code (i posted earlier) does not give the right result.

Maybe you could give me some idea about situations where @.@.rowcount could fail.

Thanks and Regards,
Parita|||I honestly have never seen @.@.rowcount fail.

I have seen code where the developer thinks @.@.rowcount faild but it turned out that the query was not returning or updateing the number of rows the developer thought would be effected.

The other situation I have seen is that @.@.rowcount is not caputered right after the query is executed or @.@.rowcount is captured and the developer printed @.@.rowcount rather than the local variable holding the rowcount for the query in question!

here is what I would do to start debugging this problem:
DECLARE @.no_of_rows int
DECLARE @.curr_prnt_cmp_convert char(5)

-- ---------------------------
-- added by psy
-- ---------------------------
declare @.Debug tinyint
, @.RowCount int
-- ---------------------------

SELECT @.local_cmps_loop = 1,
@.master_child_loop = 1,
@.acct_list_loop = 1,
@.master_child2_loop = 1,
@.no_of_rows = 0,
@.curr_prnt_cmp_convert = ' '

-- ---------------------------
-- added by psy
-- ---------------------------
set @.Debug = 1
-- ---------------------------

SET NOCOUNT ON

/* -- Temporary Tables Creation -- */
CREATE TABLE #local_cmps (cmp_int smallint, org_flg tinyint, pflg tinyint)
CREATE TABLE #master_child(bus_int smallint, prnt_cmp_int smallint, chld_cmp_int smallint, pflg tinyint)
CREATE TABLE #acct_list (bus_int smallint, prnt_cmp_int smallint, acct_int int)

/* -- Insert all Local Components -- */
INSERT INTO #local_cmps (cmp_int, org_flg, pflg)
SELECT DISTINCT cmp_int, origin_flg, 0
FROM tbl_sd_components
WHERE origin_flg = 1

-- ---------------------------
-- added by psy
-- ---------------------------
set @.RowCount = @.@.rowcount

if (@.Debug <> 0)
raiserror('Records inserted #local_cmps @.RowCount:%d',0,1,@.RowCount) with nowait
-- ---------------------------

/* -- Get Fiscal Year from Data Base -- */
-- ---------------------------
-- This can be unpredictable! @.fiscal_year will hold the first value found in the num_data
-- attribute where sys_ctl_typ = 1. There is no guarente you will get the same result twice
-- if there are several records that meet the where clause!
-- ---------------------------
SELECT @.fiscal_year = num_data
FROM tbl_sd_sys_control
WHERE sys_ctl_typ = 1

-- ---------------------------
-- added by psy
-- ---------------------------
set @.RowCount = @.@.rowcount

if (@.Debug <> 0)
raiserror('After Select @.fiscal_year @.RowCount:%d',0,1,@.RowCount) with nowait
-- ---------------------------

/* -- Start Buiding Tables for Local Components -- */
WHILE (@.local_cmps_loop = 1)

/* WHILE ((SELECT COUNT(*) FROM #local_cmps WHERE pflg = 0) > 0) */
BEGIN

/*LEAPMIGRA : Commented and added TOP 1 to subsequect SELECT ; set rowcount 1 */
/* -- Select the Unprocessed Parent Component -- */

-- ---------------------------
-- added by psy
-- ---------------------------
set @.RowCount = @.@.rowcount

if (@.Debug <> 0)
raiserror('@.local_cmps_loop:%d, @.master_child_loop:%d, @.acct_list_loop:%d, @.master_child2_loop:%d, @.no_of_rows:%d, @.curr_prnt_cmp_convert:%s',
0,1,@.local_cmps_loop, @.master_child_loop, @.acct_list_loop, @.master_child2_loop, @.no_of_rows, @.curr_prnt_cmp_convert) with nowait
-- ---------------------------

SELECT TOP 1 @.curr_prnt_cmp = cmp_int
FROM #local_cmps
WHERE pflg = 0
SELECT @.no_of_rows = @.@.ROWCOUNT

IF (@.no_of_rows = 0)
BREAK /* WHILE (@.local_cmps_loop = 1)*/

-- ---------------------------
-- added by psy
-- ---------------------------
end
-- ---------------------------

I would bet the problem is some where in your code or your assumptions of the data or how the code is working! I don't see anything inherently wrong with your code but you have not posted the entire sp either.|||Hi Paul,

I have attached here the procedure code. The solution i found was to have a select count query instead of @.@.rowcount and it is working now.

But why @.@.rowcount would not work is a big dilemma.

Thanks

Parita

@@ROWCOUNT AND TRANSACTION

I was testing some checking techniques to add to my SPs while retreiving data or inserting a series of reocords to a series of tables.

Check this testing small piece of code:

begin transaction t1select * from roles where rolename = 'student'if @.@.rowcount = 0goto cleanupselect * from usersif @.@.rowcount = 0goto cleanupcommit transaction t1goto endupcleanup:rollback transaction t1SET ROWCOUNT 0endup:print @.@.rowcount


On one of the testing cases: I made the first query return 1 record and the second returned 5 records, so we ended up at the label "endup", I printed out the RowCount it was 0, does the commit transaction reset that variable?

In addition, are there smart and effective techniques to check against validity of the query statements inside the SP, for example, I can use @.@.ERROR and @.@.ROWCOUNT in a transaction based SP to know if I proceed with sub queries, are there more stuff like that?

Regards

Bilal,

Actually I don't know if commit transaction resets the@.@.rowcount field, but from my experience the only way to use the @.@.rowcount andthe @.@.error fields, is to declare local variables and immediately after DML statementscopy the @.@.rowcount and @.@.error fields to the local variable, for example:

Declare @.xRowCount int

Declare @.xError int

Select ……

Select @.xRowCount = @.@.rowcount, @.xError = @.@.Error

Following this method you are sure that the values don't get"messed up". I always insert this "copystatement" after select, insert, update and delete statements.

BTW:

Why do you have the SET Rowcount 0 after the rollback statement(The set rowcount 0 has nothing to do with the value in the @.@.rowcountSmile [:)])?And why do you use transactions in this example (I mean as long as you justhave select statements and none update, insert or delete statements?).

|||

Hello:

Thanks for the reply.

I usually use transactions when I have update, insert or delete and off ocurse multiple statements need to be executed. I used it here to show something, wierd for me at leastSmile [:)]. The first statement returned @.@.ROWCOUNT = 1, the second 5, and the final result (ROWSCOUNT value) was 0 and that made me think of the effect of the transaction on RowCount.

Thanks for the hints.

Regards

|||Hi.

You are right. The commit transaction reset the rowcount to 0 (at least according to the SqlServer 2005 documentation).

The documentation stats that:
Statementssuch as USE, SET <option>, DEALLOCATE CURSOR, CLOSE CURSOR, BEGIN TRANSACTION or COMMIT TRANSACTION reset the ROWCOUNT value to 0.

Mark the words "Such as", meaning you can't be sure about the other statements. In other words, never trust the @.@.rowcount except right after a select, insert, update or delete statement.

I agree that is't a bit wired.

@@ROWCOUNT = 0 in a trigger

I'm going over some triggers in an old database we have and have come
accross the following...
...
IF (@.ROWCOUNT = 0)
RETURN
...
Can a trigger ever fire if zero rows were affected? Should I remove this
from the trigger?
Thanks.>> Can a trigger ever fire if zero rows were affected?
Yes, the trigger will fire once the corresponding DML is invoked. The number
of rows has no impact on its execution.
As a recommended practice, you should not.
Anith|||> Can a trigger ever fire if zero rows were affected? Should I remove this
> from the trigger?
Yes it will be fired. Just be careful using "set nocount on" before
inquiring for @.@.rowcount.
Example:
create table t1 (
c1 int not null default(0)
)
go
create trigger tr_t1_ins on t1
for insert
as
set nocount on
print '(' + ltrim(@.@.rowcount) + ' row(s) inserted' + ')'
go
create trigger tr_t1_ins_1 on t1
for insert
as
print '(' + ltrim(@.@.rowcount) + ' row(s) inserted' + ')'
go
create trigger tr_t1_upd on t1
for update
as
print '(' + ltrim(@.@.rowcount) + ' row(s) updated' + ')'
go
create trigger tr_t1_del on t1
for delete
as
print '(' + ltrim(@.@.rowcount) + ' row(s) deleted' + ')'
go
insert into t1 default values
go
update t1
set c1 = 1
where c1 = 2
go
delete t1
where c1 = 2
go
drop table t1
go
AMB
"C-W" wrote:

> I'm going over some triggers in an old database we have and have come
> accross the following...
> ...
> IF (@.ROWCOUNT = 0)
> RETURN
> ...
> Can a trigger ever fire if zero rows were affected? Should I remove this
> from the trigger?
> Thanks.
>
>|||Thanks for the information,
Chris
"C-W" <nomailplease@.microsoft.nospam> wrote in message
news:u25d8jPnFHA.3480@.TK2MSFTNGP10.phx.gbl...
> I'm going over some triggers in an old database we have and have come
> accross the following...
> ...
> IF (@.ROWCOUNT = 0)
> RETURN
> ...
> Can a trigger ever fire if zero rows were affected? Should I remove this
> from the trigger?
> Thanks.
>|||As others mentioned, the trigger will fire once per the corresponding
statement. This includes 0, 1, >1 affected rows.
In some cases you may want to apply different logic depending on the number
of affected rows. @.@.rowcount is your best tool to achieve this:
IF @.@.rowcount - 0 RETURN;
IF @.@.rowcount = 1
BEGIN -- 1 affected row logic
..
END
ELSE
BEGIN -- >1 affected rows logic
..
END
BG, SQL Server MVP
www.SolidQualityLearning.com
"C-W" <nomailplease@.microsoft.nospam> wrote in message
news:u25d8jPnFHA.3480@.TK2MSFTNGP10.phx.gbl...
> I'm going over some triggers in an old database we have and have come
> accross the following...
> ...
> IF (@.ROWCOUNT = 0)
> RETURN
> ...
> Can a trigger ever fire if zero rows were affected? Should I remove this
> from the trigger?
> Thanks.
>

@@ROWCOUNT

How can I return the number of rows returned by a select statement such as
the following one that returns zero in @.Qty ?
Alter Procedure GetMonitors
(
@.Qty INT OUTPUT
)
As
SELECT a.Suburb, a.State FROM
(
SELECT Suburb, State FROM Monitors
UNION
SELECT Suburb, State FROM Properties
WHERE Delisted Is Null
) a
GROUP BY Suburb, State
SET @.Qty = @.@.ROWCOUNT
return
Thanks in advance...Below work just fine for me... Did you define the parameter as out when you
call the proc?
USE pubs
GO
ALTER PROC p
@.qty int OUT
AS
SELECT au_lname, au_fname FROM authors
SET @.qty = @.@.ROWCOUNT
GO
--Prove that it works:
DECLARE @.rows int
EXEC p @.qty = @.rows OUT
PRINT @.rows
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"McHenry" <mchenry@.mchenry.com> wrote in message
news:44350412$0$20647$5a62ac22@.per-qv1-newsreader-01.iinet.net.au...
> How can I return the number of rows returned by a select statement such as
the following one that
> returns zero in @.Qty ?
> Alter Procedure GetMonitors
> (
> @.Qty INT OUTPUT
> )
> As
> SELECT a.Suburb, a.State FROM
> (
> SELECT Suburb, State FROM Monitors
> UNION
> SELECT Suburb, State FROM Properties
> WHERE Delisted Is Null
> ) a
> GROUP BY Suburb, State
> SET @.Qty = @.@.ROWCOUNT
> return
>
> Thanks in advance...
>|||Thanks... my mistake !
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:OMCL8TXWGHA.1564@.TK2MSFTNGP03.phx.gbl...
> Below work just fine for me... Did you define the parameter as out when
> you call the proc?
> USE pubs
> GO
> ALTER PROC p
> @.qty int OUT
> AS
> SELECT au_lname, au_fname FROM authors
> SET @.qty = @.@.ROWCOUNT
> GO
> --Prove that it works:
> DECLARE @.rows int
> EXEC p @.qty = @.rows OUT
> PRINT @.rows
>
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "McHenry" <mchenry@.mchenry.com> wrote in message
> news:44350412$0$20647$5a62ac22@.per-qv1-newsreader-01.iinet.net.au...
>

@@rowcount

Hello Experts,
I'm a little bit , see my code below:
declare @.a as tinyint
set @.a = 3
Print @.@.rowcount
why @.@.rowcount has the value 1? I didn't select any row.
Thanks in advance@.@.ROWCOUNT always populate the value of rows affected by the last operation.
Variable assignment is considered as a single row operation.
See below
declare @.a as tinyint
set @.a = 3
Print @.@.rowcount
Print @.@.rowcount
Roji. P. Thomas
Net Asset Management
https://www.netassetmanagement.com
"x-rays" <xrays@.discussions.microsoft.com> wrote in message
news:03B80B32-7AC0-423D-BA2B-7DCBD3B85C21@.microsoft.com...
> Hello Experts,
> I'm a little bit , see my code below:
> declare @.a as tinyint
> set @.a = 3
> Print @.@.rowcount
> why @.@.rowcount has the value 1? I didn't select any row.
> Thanks in advance|||Great, I got problems now, I'll better hurry up.
Thank u Thomas.
"Roji. P. Thomas" wrote:

> @.@.ROWCOUNT always populate the value of rows affected by the last operatio
n.
> Variable assignment is considered as a single row operation.
> See below
> declare @.a as tinyint
> set @.a = 3
> Print @.@.rowcount
> Print @.@.rowcount
>
>
> --
> Roji. P. Thomas
> Net Asset Management
> https://www.netassetmanagement.com
>
> "x-rays" <xrays@.discussions.microsoft.com> wrote in message
> news:03B80B32-7AC0-423D-BA2B-7DCBD3B85C21@.microsoft.com...
>
>|||It is the 'forget' issue that i was referring to (dbcc checkident ').
I was not aware of the instead of trigger issue - thanks for pointing that
out.
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:OlOx3uEiFHA.2072@.TK2MSFTNGP14.phx.gbl...
> In what way? To my knowledge, there has been no change to the @.@.IDENTITY
> function since 6.0 (when it was introduced).
> There has been improvements in the handling of identity in general, a
> major improvement between 6.5 and 7.0, there 6.5 could "forget" the
> current value. That was not related to @.@.IDENTITY function per se.
>
> Yes, SCOPE_IDENTITY() is the obvious choice. However, watch out for this
> if you are using instead of triggers!
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
> Blog: http://solidqualitylearning.com/blogs/tibor/
>
> "Mercury" <me@.spam.com> wrote in message
> news:db4jon$q7b$1@.lust.ihug.co.nz...
>

@@rowcount

I am using a combination of SQL Server 6.5 and 2000.

If I issue a SELECT statement in 6.5 and then query @.@.ROWCOUNT I get the correct value of it, e.g.
SELECT * FROM EMPLOYEES
IF @.@.ROWCOUNT > 0
...etc

But in SQL Server 2000, I only get the correct value if I SELECT it after, like this, e.g.
SELECT * FROM EMPLOYEES
SELECT @.@.ROWCOUNT
IF @.@.ROWCOUNT > 0
...etc

And it also seems to work in 2000 if you put @.@.ROWCOUNT into a variable, and query the variable.
Has anyone alse had this problem, and is it a bug in 2000 ?

Thanks,

itsmarkdavies@.hotmail.com@.@.rowcount works exactly the same in sql2k.

e.g.
declare @.cnt int
select * from employees
select @.cnt=@.@.rowcount
if @.cnt>0
begin
print 'you get @.@.rowcount fine'
end

@@ROWCOUNT

Hi all.
Why doesn't this query return number of affected rows?
UPDATE tblOrderPackages
SET packageIsSend = 1
WHERE id = 134
SELECT @.@.ROWCOUNT AS rowsAffected
Thanks,
Sharon.It should. Is this in a stored procedure or something? What do you get as a
result?
MC
"Sharon" <nothing@.null.void> wrote in message
news:u4Op3j9$FHA.1872@.TK2MSFTNGP10.phx.gbl...
> Hi all.
> Why doesn't this query return number of affected rows?
> UPDATE tblOrderPackages
> SET packageIsSend = 1
> WHERE id = 134
> SELECT @.@.ROWCOUNT AS rowsAffected
> Thanks,
> Sharon.
>|||Hi,
Its a simple query, not in a stored procedure.
When trying to get "rowsAffected" from then result set, i get this:
Item cannot be found in the collection
Sharon.
"MC" <marko_culo#@.#yahoo#.#com#> wrote in message
news:uqTzat9$FHA.3568@.TK2MSFTNGP09.phx.gbl...
> It should. Is this in a stored procedure or something? What do you get as
> a result?
>
> MC
>
> "Sharon" <nothing@.null.void> wrote in message
> news:u4Op3j9$FHA.1872@.TK2MSFTNGP10.phx.gbl...
>|||When i run this in the query analyzer, it works.
"Sharon" <nothing@.null.void> wrote in message
news:%23nheAw9$FHA.984@.tk2msftngp13.phx.gbl...
> Hi,
> Its a simple query, not in a stored procedure.
> When trying to get "rowsAffected" from then result set, i get this:
> Item cannot be found in the collection
> Sharon.
> "MC" <marko_culo#@.#yahoo#.#com#> wrote in message
> news:uqTzat9$FHA.3568@.TK2MSFTNGP09.phx.gbl...
>|||How are you reading this? Perhaps this is not an sql problem?
MC
"Sharon" <nothing@.null.void> wrote in message
news:%23nheAw9$FHA.984@.tk2msftngp13.phx.gbl...
> Hi,
> Its a simple query, not in a stored procedure.
> When trying to get "rowsAffected" from then result set, i get this:
> Item cannot be found in the collection
> Sharon.
> "MC" <marko_culo#@.#yahoo#.#com#> wrote in message
> news:uqTzat9$FHA.3568@.TK2MSFTNGP09.phx.gbl...
>|||Hi
Depending on your settings, it might be in the 2nd recordset returned.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"MC" <marko_culo#@.#yahoo#.#com#> wrote in message
news:O9T4979$FHA.436@.TK2MSFTNGP10.phx.gbl...
> How are you reading this? Perhaps this is not an sql problem?
>
> MC
>
> "Sharon" <nothing@.null.void> wrote in message
> news:%23nheAw9$FHA.984@.tk2msftngp13.phx.gbl...
>|||From asp page:
sql = "UPDATE tblOrderPackages SET packageIsSend = 1 WHERE id = 134 SELECT
@.@.ROWCOUNT AS rowsAffected"
rowsAffected = dbConn.Execute(sql)("rowsAffected")
"MC" <marko_culo#@.#yahoo#.#com#> wrote in message
news:O9T4979$FHA.436@.TK2MSFTNGP10.phx.gbl...
> How are you reading this? Perhaps this is not an sql problem?
>
> MC
>
> "Sharon" <nothing@.null.void> wrote in message
> news:%23nheAw9$FHA.984@.tk2msftngp13.phx.gbl...
>|||Thanks Mike.
This works:
rowsAffected = db.execute(sql).NextRecordset()("rowsAffected")
"Mike Epprecht (SQL MVP)" <mike@.epprecht.net> wrote in message
news:uZn12$9$FHA.1408@.TK2MSFTNGP15.phx.gbl...
> Hi
> Depending on your settings, it might be in the 2nd recordset returned.
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "MC" <marko_culo#@.#yahoo#.#com#> wrote in message
> news:O9T4979$FHA.436@.TK2MSFTNGP10.phx.gbl...
>|||Sharon wrote on Tue, 13 Dec 2005 14:26:01 +0200:

> From asp page:
> sql = "UPDATE tblOrderPackages SET packageIsSend = 1 WHERE id = 134 SELECT
> @.@.ROWCOUNT AS rowsAffected"
> rowsAffected = dbConn.Execute(sql)("rowsAffected")
Try adding SET NOCOUNT ON at the start - the first recordset returned is
returning the number of rows updated by the UPDATE statement.
Dan

@@RowCount

I want to run one of two SELECT statements, one with a Join the other
without, depending on wheteher the Join fails because of an unrelated record
.
The second statement should always return one row as the @.RequestID value
being passed comes from a Tree selection. But no row is returned. Where am I
going wrong? TIA
I am using:
CREATE PROCEDURE tdGetRequestor
@.RequestID BigInt
AS
SELECT tblRequests.RequestID, tblRequests.RequestedBy,
tblRequests.RequestDate, tblRequests.RequestorSectionID,
tblSections.SectionName AS RequestorSection
FROM tblRequests
INNER JOIN tblSections ON tblRequests.RequestorSectionID =
tblSections.SectionID
WHERE tblRequests.RequestID = @.RequestID
IF @.@.ROWCOUNT=0
BEGIN
SELECT RequestID, RequestedBy, RequestDate,RequestorSectionID
FROM tblRequests
WHERE tblRequests.RequestID = @.RequestID
END
GOHave you tried the second query in outside of the SP by providing @.RequestID
manually?
"td" <td@.discussions.microsoft.com> wrote in message
news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
>I want to run one of two SELECT statements, one with a Join the other
> without, depending on wheteher the Join fails because of an unrelated
> record.
> The second statement should always return one row as the @.RequestID value
> being passed comes from a Tree selection. But no row is returned. Where am
> I
> going wrong? TIA
> I am using:
> CREATE PROCEDURE tdGetRequestor
> @.RequestID BigInt
> AS
> SELECT tblRequests.RequestID, tblRequests.RequestedBy,
> tblRequests.RequestDate, tblRequests.RequestorSectionID,
> tblSections.SectionName AS RequestorSection
> FROM tblRequests
> INNER JOIN tblSections ON tblRequests.RequestorSectionID =
> tblSections.SectionID
> WHERE tblRequests.RequestID = @.RequestID
> IF @.@.ROWCOUNT=0
> BEGIN
> SELECT RequestID, RequestedBy, RequestDate,RequestorSectionID
> FROM tblRequests
> WHERE tblRequests.RequestID = @.RequestID
> END
> GO|||I'm not sure there is an use for RowCount here. Is there a reason why you
can't use an outer join? This should return the same results, with NULL for
tblSections.SectionName if a related record does not exist.
CREATE PROCEDURE tdGetRequestor
@.RequestID BigInt
AS
SELECT
tblRequests.RequestID
, tblRequests.RequestedBy
, tblRequests.RequestDate
, tblRequests.RequestorSectionID
, tblSections.SectionName AS RequestorSection
FROM tblRequests
LEFT OUTER JOIN tblSections
ON tblRequests.RequestorSectionID = tblSections.SectionID
WHERE tblRequests.RequestID = @.RequestID
GO
"td" <td@.discussions.microsoft.com> wrote in message
news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
> I want to run one of two SELECT statements, one with a Join the other
> without, depending on wheteher the Join fails because of an unrelated
record.
> The second statement should always return one row as the @.RequestID value
> being passed comes from a Tree selection. But no row is returned. Where am
I
> going wrong? TIA
> I am using:
> CREATE PROCEDURE tdGetRequestor
> @.RequestID BigInt
> AS
> SELECT tblRequests.RequestID, tblRequests.RequestedBy,
> tblRequests.RequestDate, tblRequests.RequestorSectionID,
> tblSections.SectionName AS RequestorSection
> FROM tblRequests
> INNER JOIN tblSections ON tblRequests.RequestorSectionID =
> tblSections.SectionID
> WHERE tblRequests.RequestID = @.RequestID
> IF @.@.ROWCOUNT=0
> BEGIN
> SELECT RequestID, RequestedBy, RequestDate,RequestorSectionID
> FROM tblRequests
> WHERE tblRequests.RequestID = @.RequestID
> END
> GO|||While I agree with Jim that you proably could use an outer join for this
(almost assuredly) have you tried to run this in Query Analyzer? See what
happens there. If you get two result sets, then it is probably something in
how you are trying to deal with 2 resultsets (which would be a question for
someone in the newsgroup that corresponds to your language (programming
language, of course :))
----
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP
"Arguments are to be avoided: they are always vulgar and often convincing."
(Oscar Wilde)
"td" <td@.discussions.microsoft.com> wrote in message
news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
>I want to run one of two SELECT statements, one with a Join the other
> without, depending on wheteher the Join fails because of an unrelated
> record.
> The second statement should always return one row as the @.RequestID value
> being passed comes from a Tree selection. But no row is returned. Where am
> I
> going wrong? TIA
> I am using:
> CREATE PROCEDURE tdGetRequestor
> @.RequestID BigInt
> AS
> SELECT tblRequests.RequestID, tblRequests.RequestedBy,
> tblRequests.RequestDate, tblRequests.RequestorSectionID,
> tblSections.SectionName AS RequestorSection
> FROM tblRequests
> INNER JOIN tblSections ON tblRequests.RequestorSectionID =
> tblSections.SectionID
> WHERE tblRequests.RequestID = @.RequestID
> IF @.@.ROWCOUNT=0
> BEGIN
> SELECT RequestID, RequestedBy, RequestDate,RequestorSectionID
> FROM tblRequests
> WHERE tblRequests.RequestID = @.RequestID
> END
> GO|||Save @.@.rowcount in an integer variable immediately after the Transact-SQL
statement completes. The value of the variable can be used later.
declare @.rowcount int
set @.rowcount = @.@.rowcount
HTH
Rajesh Peddireddy
"td" wrote:

> I want to run one of two SELECT statements, one with a Join the other
> without, depending on wheteher the Join fails because of an unrelated reco
rd.
> The second statement should always return one row as the @.RequestID value
> being passed comes from a Tree selection. But no row is returned. Where am
I
> going wrong? TIA
> I am using:
> CREATE PROCEDURE tdGetRequestor
> @.RequestID BigInt
> AS
> SELECT tblRequests.RequestID, tblRequests.RequestedBy,
> tblRequests.RequestDate, tblRequests.RequestorSectionID,
> tblSections.SectionName AS RequestorSection
> FROM tblRequests
> INNER JOIN tblSections ON tblRequests.RequestorSectionID =
> tblSections.SectionID
> WHERE tblRequests.RequestID = @.RequestID
> IF @.@.ROWCOUNT=0
> BEGIN
> SELECT RequestID, RequestedBy, RequestDate,RequestorSectionID
> FROM tblRequests
> WHERE tblRequests.RequestID = @.RequestID
> END
> GO|||Good thinking! I'm glad I thought of that (=: (or should have thought of tha
t)
"Jim Underwood" wrote:

> I'm not sure there is an use for RowCount here. Is there a reason why you
> can't use an outer join? This should return the same results, with NULL f
or
> tblSections.SectionName if a related record does not exist.
> CREATE PROCEDURE tdGetRequestor
> @.RequestID BigInt
> AS
> SELECT
> tblRequests.RequestID
> , tblRequests.RequestedBy
> , tblRequests.RequestDate
> , tblRequests.RequestorSectionID
> , tblSections.SectionName AS RequestorSection
> FROM tblRequests
> LEFT OUTER JOIN tblSections
> ON tblRequests.RequestorSectionID = tblSections.SectionID
> WHERE tblRequests.RequestID = @.RequestID
> GO
> "td" <td@.discussions.microsoft.com> wrote in message
> news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
> record.
> I
>
>|||Yes. It works fine. As I mentioned, the second statement will always return
a
row.
"Leila" wrote:

> Have you tried the second query in outside of the SP by providing @.Request
ID
> manually?
>
> "td" <td@.discussions.microsoft.com> wrote in message
> news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
>
>|||Hello Louis, Thanks for your input.
I did take Jim's advise & it works fine.
On your suggestion I have run the query in Query Analyser and it does run
correctly. In VB .Net the Reader is reporting that .HasRows is false.
Thanks to all for your suggestions
What gets returned by SQL Server in a situation such as this? It does seem
that it is reporting the zero rows back from the first query and, perhaps,
returning the result of the second as well?
In Query Analyser two distinct results ARE displayed. I will write some more
code and check what is happening in VB .Net.
td
"Louis Davidson" wrote:

> While I agree with Jim that you proably could use an outer join for this
> (almost assuredly) have you tried to run this in Query Analyzer? See what
> happens there. If you get two result sets, then it is probably something
in
> how you are trying to deal with 2 resultsets (which would be a question fo
r
> someone in the newsgroup that corresponds to your language (programming
> language, of course :))
> --
> ----
--
> Louis Davidson - http://spaces.msn.com/members/drsql/
> SQL Server MVP
> "Arguments are to be avoided: they are always vulgar and often convincing.
"
> (Oscar Wilde)
> "td" <td@.discussions.microsoft.com> wrote in message
> news:6DC4AB4F-DEF2-478E-B873-30422C1207AF@.microsoft.com...
>
>

@@rowcount

I want to do something like this.
SELECT *
FROM dbo.Contact [C]
-- If any rows are returned then return to front end.
IF @.@.rowcount > 0
Begin
GOTO FinishSuccessModule
End
-- But i had doubt here
We will never be sure that @.@.RowCount is giving the row count of the query
mentioned above since in a heavy concurrent scenario (as we have in our db
and its growing since our user base is also growing) before your query and
the checking of @.@.RowCount there might be another select fired by another
process or transaction which updates @.@.Rowcount which in turn give you
incorrect values.
how can we implement the same functionality using some other way, i dont
want If exists as there are around 6-7 conditions which are totally
select..if any one of them return record then come out else continue with
other sql st.
does @.@.rowcount create issues as mentioned above and second can we avoid
that using some other functionality.
Sanjay
Sanjay
No, rowcount is safe.
Bojidar Alexandrov
"Sanjay" <Sanjay@.discussions.microsoft.com> wrote in message
news:7276DE0A-F23B-403B-BEE5-C83E51FA71FC@.microsoft.com...
> I want to do something like this.
> SELECT *
> FROM dbo.Contact [C]
> -- If any rows are returned then return to front end.
> IF @.@.rowcount > 0
> Begin
> GOTO FinishSuccessModule
> End
> -- But i had doubt here
> We will never be sure that @.@.RowCount is giving the row count of the
query
> mentioned above since in a heavy concurrent scenario (as we have in our db
> and its growing since our user base is also growing) before your query and
> the checking of @.@.RowCount there might be another select fired by another
> process or transaction which updates @.@.Rowcount which in turn give you
> incorrect values.
> how can we implement the same functionality using some other way, i dont
> want If exists as there are around 6-7 conditions which are totally
> select..if any one of them return record then come out else continue with
> other sql st.
> does @.@.rowcount create issues as mentioned above and second can we avoid
> that using some other functionality.
> --
> Sanjay
> --
> Sanjay
|||If all you need to know is are "any" rows returned and don't care how many,
I would change the initial query to SELECT TOP 1 * FROM dbo.Contact (C). If
your contact table gets thousands of rows, why go thru and read them all
when you just need to know "do I get back at least 1 row"? And to be more
specific, you don't need a SELECT *. Pick one narrow column for your
select. Something like select top 1 ContactID from dbo.contact (c). This
is a lot more efficient.
"Bojidar Alexandrov" <bojo_do_not_spam@.kodar.net> wrote in message
news:eWegGSspEHA.3244@.tk2msftngp13.phx.gbl...[vbcol=seagreen]
> No, rowcount is safe.
> Bojidar Alexandrov
> "Sanjay" <Sanjay@.discussions.microsoft.com> wrote in message
> news:7276DE0A-F23B-403B-BEE5-C83E51FA71FC@.microsoft.com...
> query
db[vbcol=seagreen]
and[vbcol=seagreen]
another[vbcol=seagreen]
with
>

@@rowcount

I want to do something like this.
SELECT *
FROM dbo.Contact [C]
-- If any rows are returned then return to front end.
IF @.@.rowcount > 0
Begin
GOTO FinishSuccessModule
End
-- But i had doubt here
We will never be sure that @.@.RowCount is giving the row count of the query
mentioned above since in a heavy concurrent scenario (as we have in our db
and its growing since our user base is also growing) before your query and
the checking of @.@.RowCount there might be another select fired by another
process or transaction which updates @.@.Rowcount which in turn give you
incorrect values.
how can we implement the same functionality using some other way, i dont
want If exists as there are around 6-7 conditions which are totally
select..if any one of them return record then come out else continue with
other sql st.
does @.@.rowcount create issues as mentioned above and second can we avoid
that using some other functionality.
--
Sanjay
--
SanjayNo, rowcount is safe.
Bojidar Alexandrov
"Sanjay" <Sanjay@.discussions.microsoft.com> wrote in message
news:7276DE0A-F23B-403B-BEE5-C83E51FA71FC@.microsoft.com...
> I want to do something like this.
> SELECT *
> FROM dbo.Contact [C]
> -- If any rows are returned then return to front end.
> IF @.@.rowcount > 0
> Begin
> GOTO FinishSuccessModule
> End
> -- But i had doubt here
> We will never be sure that @.@.RowCount is giving the row count of the
query
> mentioned above since in a heavy concurrent scenario (as we have in our db
> and its growing since our user base is also growing) before your query and
> the checking of @.@.RowCount there might be another select fired by another
> process or transaction which updates @.@.Rowcount which in turn give you
> incorrect values.
> how can we implement the same functionality using some other way, i dont
> want If exists as there are around 6-7 conditions which are totally
> select..if any one of them return record then come out else continue with
> other sql st.
> does @.@.rowcount create issues as mentioned above and second can we avoid
> that using some other functionality.
> --
> Sanjay
> --
> Sanjay|||If all you need to know is are "any" rows returned and don't care how many,
I would change the initial query to SELECT TOP 1 * FROM dbo.Contact (C). If
your contact table gets thousands of rows, why go thru and read them all
when you just need to know "do I get back at least 1 row"? And to be more
specific, you don't need a SELECT *. Pick one narrow column for your
select. Something like select top 1 ContactID from dbo.contact (c). This
is a lot more efficient.
"Bojidar Alexandrov" <bojo_do_not_spam@.kodar.net> wrote in message
news:eWegGSspEHA.3244@.tk2msftngp13.phx.gbl...
> No, rowcount is safe.
> Bojidar Alexandrov
> "Sanjay" <Sanjay@.discussions.microsoft.com> wrote in message
> news:7276DE0A-F23B-403B-BEE5-C83E51FA71FC@.microsoft.com...
> > I want to do something like this.
> > SELECT *
> > FROM dbo.Contact [C]
> > -- If any rows are returned then return to front end.
> > IF @.@.rowcount > 0
> > Begin
> > GOTO FinishSuccessModule
> > End
> > -- But i had doubt here
> > We will never be sure that @.@.RowCount is giving the row count of the
> query
> > mentioned above since in a heavy concurrent scenario (as we have in our
db
> > and its growing since our user base is also growing) before your query
and
> > the checking of @.@.RowCount there might be another select fired by
another
> > process or transaction which updates @.@.Rowcount which in turn give you
> > incorrect values.
> >
> > how can we implement the same functionality using some other way, i dont
> > want If exists as there are around 6-7 conditions which are totally
> > select..if any one of them return record then come out else continue
with
> > other sql st.
> >
> > does @.@.rowcount create issues as mentioned above and second can we avoid
> > that using some other functionality.
> > --
> > Sanjay
> > --
> > Sanjay
>