没有从SQL Server查询获得正确的输出

时间:2011-06-04 07:53:24

标签: sql-server-2005

ALTER PROCEDURE [dbo].[Sp_GetEmailForMailing] 
    -- Add the parameters for the stored procedure here
    @end int=1000
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT top(500) RegistrationID, EmailID from dbo.Candidate_RegistrationData
    where status_flag=1 and payment_status=2
    and RegistrationID NOT IN (SELECT top(@end) RegistrationID from dbo.Candidate_RegistrationData
    where status_flag=1 and payment_status=2) order by RegistrationID
END

这是我的存储过程。在这里我想要500行,但我从250行开始....任何人都知道为什么会发生...谢谢

2 个答案:

答案 0 :(得分:3)

用作NOT IN数据源的子查询没有ORDER BY子句。因此,查询引擎可以按其认为合适的顺序自由地获取TOP(@end)行。

答案 1 :(得分:0)

我希望你想跳过 top @end 注册,按注册ID排序

您应该尝试以下代码。

ALTER PROCEDURE [dbo].[Sp_GetEmailForMailing]   

@end int = 1000  

AS  

SET NOCOUNT ON;

BEGIN
    Select Top(500) RegistrationID, EmailID From
    (
         Select Row_Number() Over(Order by RegistrationID) as RowId, 
                   RegistrationID,     
                   EmailID,    
                   status_flag, 
                   payment_status
         From dbo.Candidate_RegistrationData
         Where status_flag = 1 and payment_status = 2
    )T
    Where RowId > @end and status_flag = 1 and payment_status = 2 
    Order By RegistrationID
End