I have a stored procedure, which contains a simple select statement:
ALTER PROCEDURE [dbo].[TransferAuditRecords]
As
SET NOCOUNT ON
SET XACT_ABORT ON
Declare @UserCode As varchar(50)
DECLARE AuditCursor CURSOR FOR
select top 1 UserCode from [AuditDatabaseServer].AuditDatabase.dbo.dbaudit where auditdate >= '2012-09-04'
Open AuditCursor
FETCH NEXT FROM AuditCursor INTO @UserCode
WHILE @@FETCH_STATUS = 0
BEGIN
Print @Usercode
FETCH NEXT FROM AuditCursor INTO @UserCode
END
Close AuditCursor
Deallocate AuditCursor
There are a few lines of code missing, which I excluded as they are irrelevant to the question.
If I execute the SQL statement without the stored procedure i.e. in SQL Studio Manager 2005 then I get a different output than if I run the stored procedure i.e. the top reference returned is different. Why are the outputs different?
I am fairly sure that the reason for this is because SQL Server uses a different execution plan for compiled code is comparison to code being run in SQL Studio Manager. I wanted to check though.
Use an ORDER BY clause to predictably indicate which row is selected.
e.g. select top 1… order by auditdate
Unrelated:: is the use of a cursor required by part of the code you removed? I guess so, otherwise a simpler “select top 1 @UserCode = UserCode from…” would be enough.