如何编写需要创建id的存储过程,然后在同一过程中使用?

时间:2013-01-16 17:12:16

标签: sql stored-procedures insert

我正在尝试编写一个存储过程,将新用户(NonMembers表)的详细信息写入数据库,然后在代码的下一部分中为该用户使用自动生成的id将该用户注册到比赛(登记表)。我这样做的尝试如下,但显然我的SQL技能距离他们需要的地方很远?

非常感谢所有帮助。

ALTER PROCEDURE [dbo].[RegisterNonMember]
    @CompetitionId INTEGER,
    @IsMember BIT,
    @FirstName  NVARCHAR(50),
    @Surname  NVARCHAR(50),
    @Handicap INTEGER,
    @Club NVARCHAR(50),
    @CountyId INTEGER,
    @CountryId INTEGER,
    @PlayersStartTime TIME

AS
BEGIN

DECLARE @NonMember TABLE
    (NonMemberId INTEGER,
    FirstName  NVARCHAR(50),
    Surname  NVARCHAR(50),
    Handicap INTEGER,
    Club NVARCHAR(50),
    CountyId INTEGER,
    CountryId INTEGER
) 
INSERT INTO [dbo].[NonMembers]
           (
           FirstName
           ,Surname
           ,[Handicap]
           ,[Club]
           ,CountyId
           ,CountryId       
)
     VALUES
           (@FirstName
           ,@Surname
           ,@Handicap
           ,@Club
           ,@CountyId
           ,@CountryId
           )

--UPDATE    @NonMember
--SET       [@NonMember].NonMemberId = [dbo].[NonMembers].[NonMemberId]
--FROM  [dbo].[NonMembers]
--JOIN  @NonMember ON [@NonMember].NonMemberId = [dbo].[NonMembers].[NonMemberId]
--WHERE @NonMember.FirstName = [dbo].[NonMembers].[FirstName]
--AND       @NonMember.Surname = [dbo].[NonMembers].[Surname]
--AND       @NonMember.Handicap = [dbo].[NonMembers].[Handicap]
--AND       @NonMember.Club = [dbo].[NonMembers].[Club]

DECLARE @Registration TABLE
    (CompetitionId INTEGER,
    IsMember BIT,
    NonMemberId INTEGER,
    PlayersStartTime TIME
    )

INSERT INTO [dbo].[Registration]
            (
            [CompetitionId]
            ,[IsMember]
            ,[NonMemberId]
            ,[PlayersStartTime])
    VALUES
            (@CompetitionId
            ,@IsMember
            ,@NonMemberId
            ,@PlayersStartTime)  
END

1 个答案:

答案 0 :(得分:3)

INSERT添加:

之后
DECLARE @UserID INT
SELECT @UserID = SCOPE_IDENTITY()