Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Tuesday, March 20, 2012

[SS2K5] : Populate a CTE from stored procedure result set

Hi,

I'd like to know if it's possible to populate/load a CTE from a stored procedure result set ?

Kind of :

USE MyDB;
GO
WITH MyCTE (Col1, Col2, Col3)
AS
(

EXECUTE myStoredProc

)
SELECT *
FROM MyCTE
GO

Thanks for your help.

Cheers,

Bertrand

A couple of options include loading your stored procedure output to a temp table:

INSERT NTO #aTempTable
EXEC yourStoredProcedure

and also converting your procedure into an function or perhaps a view and then you can join to the function or view. If the primary objective of the stored procedure is to be used as you describe it might be best from the outset to consider converting it into a function.

But also keep in mind that in many cases the temp table / stored procedure option will outperform the function.

|||

CTE in SQL Server 2005 is just syntactic sugar. It is similar to view in that the query expression of the CTE is parsed into the original query, compiled, optimized and executed. So there is no special optimization in terms of storing intermediate results in case of multiple references to the same CTE and so on. So you have few options:

1. Convert the SP to inline TVF - best performance

2. Convert the SP logic to a view

3. Convert the SP to non-inline TVF

4. Use a temporary table to store results from SP and reuse it

|||

Well in fact I have to perform a row by row operation on the sp result set. Which means using a cursor. And I know that using a cursor with a temporay table is not the best in term of performance so I thought that CTE was the best option...

But your first option could fits for my problem.

Thanks for your guidance.

|||What kind of row by row operation are you performing?|||

Well in fact I received a result set from one stored procedure. Each column in this result set become input parameters for an other stored proc I have to call.

It could be more "easy" if I had the right to modifiy the both of these stored proc but I'm not allowed to and I just can to plug my logic between these sp ....

Monday, March 19, 2012

[sql server 2005] - debug a stored procedure

hello world,

how cani debug a stored procedure under sql server 2005?

I usually sprinkle PRINT statements before and after some logical operation to know whats happening in different sections. You can also check for @.@.ERROR after every T-SQL.|||If you are working with vs studio take a look at :How to debug stored procedures in Visual Studio .NET

Sunday, March 11, 2012

[scheduling] SSIS Package fails, but scheduler reports success

I have an SSIS Package that executes a stored procedure. It turns out my stored procedure was missing.

However, the SQL Job Scheduler reported that step as success.

Can anyone tell me why?

`Le

Because your package is not exiting with an indication of success/failure.

Moved to the SSIS forum.

|||
when I run it through the command line, it indeed gives me an error code of (1).

But the Scheduler still tells me that it is successful.

`Le
|||You need to check the JOB action to take when a step fails -perhaps it is set to continue and report success.|||The step itself is trying to run a stored procedure that does not exist. The Sql schedule should report a failure, but it is not. It reports a success.

The Sql Server job says "quit with failure" when there is an error. There is clearly a different problem here.

`Le

|||

It is difficult to help you when you have all of the details and we don't. We can't see what you are doing and what happens, Your descriptions are incomplete and do not allow a good problem determination and resolution.

Please post the entire command line that you are having problems with, including any success/failure statements after it executes.

Is this being executed by the Windows Scheduler?

What version of SQL Server are you using?

|||

Arnie Rowland wrote:

It is difficult to help you when you have all of the details and we don't. We can't see what you are doing and what happens, Your descriptions are incomplete and do not allow a good problem determination and resolution.

Please post the entire command line that you are having problems with, including any success/failure statements after it executes.

Is this being executed by the Windows Scheduler?

What version of SQL Server are you using?

Thank you for your reply. I will attempt to be more detailed:

SQL SERVER: 2005
VISUAL STUDIO: 2005
SSIS File Name: Foo.dtsx
Configuration File Name: Config.dtsConfig

This config file has multiple steps, including one step that executes a Stored Procedure.

When I run this through a command line, I run it as:
dtexec.exe /FILE "\\MyServer\Foo.dtsx.dtsx" /CONFIGFILE "\\MyServer\Config.dtsConfig" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E

When it is run this way, process exits with error (1), because the Stored Procedure in question does not exist on the database. This is the correct error message.

When I run it through SQL SERVER 2005 SCHEDULER, I run it as a SSIS package, with the command line:
/FILE "\\MyServer\Foo.dtsx.dtsx" /CONFIGFILE "\\MyServer\Config.dtsConfig" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E

However, the package always exits with success.

|||if a task inside a SSIS Package fails doesn't mean that the whole package fails
and the sql agent step would only report an error if the whole package fails

so you could set the property 'Fail Package on failure' to TRUE ... in the task where you execute this stored procedure.

- paul
|||When I run the package via command line (dtexec.exe), I do get fail message:

DTExec: The package execution returned DTSER_FAILURE(1)

~Le

Tuesday, March 6, 2012

[ms sql] How to add new table to merge replication ?

Hi,
How to add new table to merge replication ?

When I do this in Enterpriise Manager i got an error:
Server: Msg 2758, Level 16, State 1, Procedure sp_addmergearticle,
Line 466
RAISERROR could not locate entry for error 20085 in sysmessages.

What is wrong ?

Thank for any help

LukOn Jul 12, 9:49 am, szaki <ljag...@.gmail.comwrote:

Quote:

Originally Posted by

Hi,
How to add new table to merge replication ?
>
When I do this in Enterpriise Manager i got an error:
Server: Msg 2758, Level 16, State 1, Procedure sp_addmergearticle,
Line 466
RAISERROR could not locate entry for error 20085 in sysmessages.
>
What is wrong ?
>
Thank for any help
>
Luk


The handy thing with that procedure is that you can open it up and
look down to the line number, and read the comments, and maybe get an
idea of what the problem is, even if the error message is missing.

Strangely, I can't find it raising 20085 at that line number - on SQL
2000 SP 4. But at that line, there is a check that all articles
contain a column marked with the rowguidcol property (and raising
error 20086). So, is that what's wrong with your table?

Damien

Saturday, February 25, 2012

[Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure

I am new to SQL Server and stored procedures and here is my problem.

I am stepping into a stored procedure ‘storedProced1’ using T-SQL debugger. ‘storedProced1’ is calling ‘storedProced2’. When I step into the following line where storedProced2’ is being executed,

exec storedProced2 @.Parameter1, @. Parameter2, @. Parameter3

I got the following message in the immediate window.

[Microsoft][ODBC SQL Server Driver][SQL Server]Could not find stored procedure 'storedProced2’.

@.RETURN_VALUE = N/A

But “storedProced2” does exists. What am I doing wrong?

Make sure that the procedure exists within the actual database and make sure that you are using the right owner declaration for this, this calling the procedure with the Routine_Schema and Routine_Name from the following query.

SELECT Routine_schema, ROutine_name
From INFORMATION_SCHEMA.Routines
WHere Routine_Name = 'storedProced2'

--> Calling EXEC <SchemaName>.<Objectname>

HTH, jens K. Suessmeyer.

http://www.sqlserver2005.de

Saturday, February 11, 2012

@return_status from SQLCLR stored procedure

I'm trying to write a VB CLR stored procedure that will set the return statu
s
to 0 or 1 depending on whether the CLR was successful or not. How do I do
that? Basically I want to use the following T-SQL code to call my CLR and
set the @.return_status
declare @.return_status int
EXEC @.return_status=My_CLR_SP
select @.return_statusI would like to know how to do this as well. Can anyone help us?
Greg Larsen wrote:
> I'm trying to write a VB CLR stored procedure that will set the return sta
tus
> to 0 or 1 depending on whether the CLR was successful or not. How do I do
> that? Basically I want to use the following T-SQL code to call my CLR and
> set the @.return_status
> declare @.return_status int
> EXEC @.return_status=My_CLR_SP
> select @.return_status|||Greg,
I found this at http://msdn2.microsoft.com/en-us/library/ms131094.aspx.
I tried it out and it works great.
Here is a really simple example:
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Function TestProc() As Int32
TestProc = 1
End Function
And the test script:
DECLARE @.result AS int
EXEC @.result = TestProc
PRINT @.result
Tom
Greg Larsen wrote:
> I'm trying to write a VB CLR stored procedure that will set the return sta
tus
> to 0 or 1 depending on whether the CLR was successful or not. How do I do
> that? Basically I want to use the following T-SQL code to call my CLR and
> set the @.return_status
> declare @.return_status int
> EXEC @.return_status=My_CLR_SP
> select @.return_status|||Thank you for the VB example.
I got mine to working by writing it in C # and doing the following:
[Microsoft.SqlServer.Server.SqlProcedure]
public static int TestProc()
{ return=1;}|||You're welcome. Thanks for posting the C# example.
Tom
Greg Larsen wrote:
> Thank you for the VB example.
> I got mine to working by writing it in C # and doing the following:
> [Microsoft.SqlServer.Server.SqlProcedure]
> public static int TestProc()
> { return=1;}

@query error

ODBC error 4604 (42000) There is no such user or group 'sa8'

this is the error message I get when I run my stored procedure that has the @.query parameter and I have been told this is a bug within sql that microsoft doesn't seem to be aware off.

Are you coming across this and what do you do to go around it?

RegardsHi:

I have found this "solution". Please check if you can use it ;)

We had a similar problem, the way we got around it was to add access rights to the TEMP directory in the Document and Settings folder on the account logged into the Server. As we had the NT Administrator account permanatley logged onto the server. If I tried to run a temp query from xp_sendmail it would fail, but if I used the administraor account it worked okay. The query writes the output file it needs to to the temp folder of which we had no access rights. Once I changed the access rights it worked okay. Did find this answer in one of the many SQL forums on the net. Hope this help you.|||I hope I can be more helper ;)

@original and stored procedures

When using @.original_{0}, how does this work if you are using a stored procedure instead of inline SQL? For example, if my update parameters are like this :

<

UpdateParameters><asp:ParameterType="String"Name="ProductType"/><asp:ParameterType="String"Name="OpportunityType"/><asp:ParameterType="Double"Name="Value"/><asp:ParameterType="String"Name="Probability"/><asp:ParameterType="Int32"Name="OpportunityID"/></UpdateParameters>

And my stored procedure like this :

CREATE procedure dbo.UpdateOpportunity

(
@.ProductType int,
@.OpportunityType int,
@.Value money,
@.Probability int,
@.OpportunityID int
)

as

update Opportunity
set ProductType = @.ProductType, OpportunityType = @.OpportunityType,
[Value] = @.Value, Probability = @.Probability
where OpportunityID = @.OpportunityID

Do I need to change both cases of @.OpportunityID in my stored procedure to @.original_OpportunityID for it to work?

Most likely. It also depends on what you have set for the conflictdetection property. If it's compareallvalues, then you'll need to accept @.original_ for each of the columns that you selected via your select statement.

@NumericVal IS NOT NULL seems not to return a boolean.

I'm trying to ensure that only of the parameters is passed to my stored procedure.

BOL says that the IS [NOT] NULL operator (language construct?) will return a boolean. An IF statement takes an expression which results in a boolean so I was surprised to find that the below code doesn't parse.

CREATE PROC sp_OneParm(
@.NumericVal float = null,
@.StringVal nvarchar(200) = null,
@.DateVal datetime = null,
@.BitVal bit = null)
AS
DECLARE @.ValCount tinyint
SET @.ValCount = 0

-- Ensure we've only got one update value specified
IF @.NumericVal IS NOT NULL @.ValCount = @.ValCount + 1
IF @.StringVal IS NOT NULL @.ValCount = @.ValCount + 1
IF @.DateVal IS NOT NULL @.ValCount = @.ValCount + 1
IF @.BitVal IS NOT NULL @.ValCount = @.ValCount + 1
IF @.ValCount > 1 RAISERROR ('Only one @.*Val paramater may be specified when calling sp_OneParm()', 16, 1)

-- Other Stuff
GO

Am I missing something simple or do I need to restructure my code to achieve the logic I want?Sure :)

IF @.NumericVal IS NOT NULL SET @.ValCount = @.ValCount + 1|||Bugger. :o
Thank-you roac.

@bitmap was not supplied to upd procedure in transactional

Initially when I had setup my transactional replication I had created it with
out taking a snapshot and by synching the databases.
Now I am trying to add new table to one of my existing publication in
production by creating scripts for ins, upd and del in test server and
deploying it to subscriber but it throws an error saying
"sp_MSupd_tablenameexpects parameter '@.bitmap', which was not supplied"
Inserts just work fine.
This is what i used to add-
exec sp_addarticle @.publication = 'Repl_Source'
, @.article = TableName
, @.source_table = TableName
, @.sync_object = null
exec sp_addsubscription @.publication = 'Repl_Source'
, @.article = TableName
, @.subscriber = SERVERNAME
, @.destination_db = 'Repl_Destination'
how many columns are in your table?
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"SQL Replication Guy" <SQLReplicationGuy@.discussions.microsoft.com> wrote in
message news:AF5F5FE4-E43C-48C6-8FF9-9739C7C3DE62@.microsoft.com...
> Initially when I had setup my transactional replication I had created it
> with
> out taking a snapshot and by synching the databases.
> Now I am trying to add new table to one of my existing publication in
> production by creating scripts for ins, upd and del in test server and
> deploying it to subscriber but it throws an error saying
> "sp_MSupd_tablenameexpects parameter '@.bitmap', which was not supplied"
> Inserts just work fine.
> This is what i used to add-
> exec sp_addarticle @.publication = 'Repl_Source'
> , @.article = TableName
> , @.source_table = TableName
> , @.sync_object = null
> exec sp_addsubscription @.publication = 'Repl_Source'
> , @.article = TableName
> , @.subscriber = SERVERNAME
> , @.destination_db = 'Repl_Destination'
>
>
|||18 columns.
If I rememebr correctly I have tested same before a 6 months agao on
different table and i rememeber it working. Not sure what changed.
"Hilary Cotter" wrote:

> how many columns are in your table?
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
> "SQL Replication Guy" <SQLReplicationGuy@.discussions.microsoft.com> wrote in
> message news:AF5F5FE4-E43C-48C6-8FF9-9739C7C3DE62@.microsoft.com...
>
>
|||Hi Hilary,
I think this is what thats happenening
- As I have scripted ins, upd and del scripts in dev environment by
generating them by running snapshot in transactional replication, those are
scripted with @.bitmap varaiable.
- Looks like the code I have used to add subscription
exec sp_addsubscription @.publication = 'Repl_Source'
, @.article = TableName
, @.subscriber = SERVERNAME
, @.destination_db = 'Repl_Destination'
is trying for ins, upd and del procs with no @.bitmap.
Instead of above code I have used
exec sp_addsubscription
@.publication = Repl_Source,
@.article = TableName,
@.subscriber = SERVERNAME,
@.destination_db = 'Repl_Destination',
@.sync_type = N'automatic',
@.subscription_type = N'pull',
@.update_mode = N'read only'
then when i made data changes it asked for snapshot to be execute dfirst and
it created sp's at destination with out bitmap
As all my other sp's were created during initial setup with bitmap i would
like them to be in sync . rather than some with bitmap variable and some with
out..
Any advise....
"SQL Replication Guy" wrote:
[vbcol=seagreen]
> 18 columns.
>
> If I rememebr correctly I have tested same before a 6 months agao on
> different table and i rememeber it working. Not sure what changed.
> "Hilary Cotter" wrote:
|||return to your publisher and in qa change to the publication database, then
recreate your replication procs by issuing a sp_scriptpublicationcustomprocs
'publicationName'
then copy what you find in the results pane, go to the subscriber, change to
the subscription database, and paste these results into qa and run them.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"SQL Replication Guy" <SQLReplicationGuy@.discussions.microsoft.com> wrote in
message news:C261558E-58A6-4810-A5E1-AB24439B9A9E@.microsoft.com...[vbcol=seagreen]
> Hi Hilary,
> I think this is what thats happenening
> - As I have scripted ins, upd and del scripts in dev environment by
> generating them by running snapshot in transactional replication, those
> are
> scripted with @.bitmap varaiable.
> - Looks like the code I have used to add subscription
> exec sp_addsubscription @.publication = 'Repl_Source'
> , @.article = TableName
> , @.subscriber = SERVERNAME
> , @.destination_db = 'Repl_Destination'
> is trying for ins, upd and del procs with no @.bitmap.
>
> Instead of above code I have used
> exec sp_addsubscription
> @.publication = Repl_Source,
> @.article = TableName,
> @.subscriber = SERVERNAME,
> @.destination_db = 'Repl_Destination',
> @.sync_type = N'automatic',
> @.subscription_type = N'pull',
> @.update_mode = N'read only'
> then when i made data changes it asked for snapshot to be execute dfirst
> and
> it created sp's at destination with out bitmap
>
> As all my other sp's were created during initial setup with bitmap i would
> like them to be in sync . rather than some with bitmap variable and some
> with
> out..
> Any advise....
>
> "SQL Replication Guy" wrote:
|||Hi Hilary,
I was trying several options soory could get to try your option but this
worked--
sp_addarticle
@.publication = 'Repl_Source',
@.article = 'TableName',
@.source_object = 'TableName',
@.destination_table = 'TableName',
@.ins_cmd = 'call sp_MSins_TableName,
@.del_cmd = 'call sp_MSdel_TableName',
@.upd_cmd = 'mcall sp_MSupd_TableName', -- MCALL CREATED bitmap in UPD sp
@.type = 'logbased',
@.pre_creation_cmd = 'drop',
@.status = 16,
@.source_owner = 'dbo',
@.vertical_partition = 'false',
@.filter = Null,
@.auto_identity_range = 'false'
and then
exec sp_addsubscription @.publication = 'Repl_Source'
, @.article = TableName
, @.subscriber = SERVERNAME
, @.destination_db = 'Repl_Destination'
"SQL Replication Guy" wrote:

> Initially when I had setup my transactional replication I had created it with
> out taking a snapshot and by synching the databases.
> Now I am trying to add new table to one of my existing publication in
> production by creating scripts for ins, upd and del in test server and
> deploying it to subscriber but it throws an error saying
> "sp_MSupd_tablenameexpects parameter '@.bitmap', which was not supplied"
> Inserts just work fine.
> This is what i used to add-
> exec sp_addarticle @.publication = 'Repl_Source'
> , @.article = TableName
> , @.source_table = TableName
> , @.sync_object = null
> exec sp_addsubscription @.publication = 'Repl_Source'
> , @.article = TableName
> , @.subscriber = SERVERNAME
> , @.destination_db = 'Repl_Destination'
>
>

Thursday, February 9, 2012

@@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

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...
>

@@IDENTITY question

Hi, friends. I got a question for @.@.IDENTITY when I was working on a C#.net project.

I use "SELECT @.@.IDENTITY, @.@.ERROR" in the stored procedure to retrieve the ID column of the row just inserted, and in my C# code, I try to access it with rdr.GetInt64(0) since ID column is bigint. However, there is a error. The type is not match. I must instead use rdr.GetDecimal(0) to access @.@.IDENTITY which is a bigint.

I got confused, anybody has any idea?

Thanks.

xufff::I got confused, anybody has any idea?

Sure. Get used to reading the documentation.

@.@.IDENTITY is a (documented, btw) variable that is defined by SQL Server. It is not created based on your data type in the ID column, it is predefined.

The documentation says that the data type of the @.@.IDENTITY variable is - numeric, which translates to decimal in the CLR.

So, according to the documentation (which I checked not to post garbage - took me 10 seconds) this is simply the expected behavior.

I would think that the reason for this is that it IS legal to have a decimal based ID field. Unusual, but legal. And they decided to use numeric for the variable type, simply because this is about the "largest" data type they can use, handling everything allowed for identity fields.

Now, all you have to do is convert this decimal to a bigint - which should not give you any problems.