在SQL Server存储过程中使用返回值

时间:2015-04-21 15:48:18

标签: sql-server-2008 stored-procedures

尝试通过从一个表中检索ID并使用该值在同一过程中检索结果来获取结果集。

这将返回正确的userID,但不返回旅行者信息。

USE [GrandCelebration]
GO
/****** Object:  StoredProcedure [dbo].[update_system_emails_audit_read_date]    Script Date: 4/21/2015 10:44:52 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Alter PROCEDURE [dbo].[GetUserID]
    @UniqueKey varchar(20)
AS


DECLARE @ReturnValue int

SELECT @ReturnValue=UserId FROM SystemEmailsAudit WHERE UniqueKey=@UniqueKey;
RETURN @ReturnValue
Go
DECLARE @ReturnValue int
Select * from LeadTravelers where CertificateID = @ReturnValue

2 个答案:

答案 0 :(得分:0)

通过修改存储过程从LeadTravelers表返回行。

USE [GrandCelebration]
GO
/****** Object:  StoredProcedure [dbo].[update_system_emails_audit_read_date]    Script Date: 4/21/2015 10:44:52 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Alter PROCEDURE [dbo].[GetUserID]
    @UniqueKey varchar(20)
AS
Begin

    DECLARE @ReturnValue int

    SELECT @ReturnValue=UserId FROM SystemEmailsAudit WHERE UniqueKey=@UniqueKey;

    Select * from LeadTravelers where CertificateID = @ReturnValue

    end 

Go

答案 1 :(得分:0)

您可以使用JOIN代替使用变量

USE [GrandCelebration]
GO
/****** Object:  StoredProcedure [dbo].[update_system_emails_audit_read_date]    Script Date: 4/21/2015 10:44:52 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Alter PROCEDURE [dbo].[GetUserID]
    @UniqueKey varchar(20)
AS
Begin

        SELECT UserId 
        FROM SystemEmailsAudit 
        WHERE UniqueKey = @UniqueKey;

        SELECT LT.* FROM LeadTravelers LT
        JOIN SystemEmailsAudit SEA 
        ON LT.CertificateID = SEA.UserId
        WHERE SEA.UniqueKey = @UniqueKey;
end 
Go