将自动增量主键插入外键表

时间:2017-10-10 12:39:35

标签: mysql database

我有2个表UserUserLoginUserLoginUser表具有外键关系。我想在这里做的是每当我通过我的API将数据插入User表时,他们的自动生成(user_id)自动插入到UserLogin表中。

User表:

user_id | user_name | user_email

UserLogin表:

user_id | user_password | user_number

因此,当我运行查询以在User表中添加名称和电子邮件时,自动增加的user_id将自动插入UserLogin表中,并提供所提供的密码和编号。我怎样才能实现这一点并且该线程是否安全?

2 个答案:

答案 0 :(得分:0)

是的,这是可能的,通常可以通过@@ identity尝试使用

之类的东西
 set nocount off;
insert into User Values("Name","Email")
declare @lastID = @@identity
insert into UserLogin values(@lastID,"Password","number")

答案 1 :(得分:0)

此代码可以帮助您

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[User](
    [user_id] [int] IDENTITY(1,1) NOT NULL,
    [user_name] [varchar](100) NULL,
    [user_email] [varchar](100) NULL,
    [salt] [uniqueidentifier] NULL,
 CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED 
(
    [user_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[UserLogin](
    [UserLoginId] [int] IDENTITY(1,1) NOT NULL,
    [user_id] [int] NULL,
    [user_password] [binary](1) NULL,
    [user_number] [int] NULL
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[User]  WITH CHECK ADD  CONSTRAINT [FK_UserLogin_User] FOREIGN KEY([user_id])
REFERENCES [dbo].[User] ([user_id])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_UserLogin_User]
GO

 CREATE PROC [dbo].[Usp_UserLogin] 
 (
 @user_name VARCHAR(100)
 ,@user_email VARCHAR(100)
 ,@user_password VARCHAR(200)
 ,@user_number INT
 )

 AS
 Begin
  SET NOCOUNT ON 
 DECLARE @Salt UNIQUEIDENTIFIER =NEWID() 
        ,@IdentityNUmber INT
        ,@responseMessage nvarchar(1000)

 BEGIN TRY

        INSERT INTO Dbo.[User]([user_name],[user_email],[salt])

       SELECT        @user_name
                    ,@user_email
                    ,@salt



        SET @IdentityNUmber=SCOPE_IDENTITY()


        INSERT INTO Dbo.[UserLogin]([user_id],[user_password],user_number)

        SELECT  
         @IdentityNUmber
        ,@user_number 
        ,HASHBYTES('SHA2_512', @user_password + CAST(@salt AS NVARCHAR(36))) 



 END TRY

  BEGIN CATCH 
          SET @responseMessage=ERROR_MESSAGE() 
      END CATCH 



 END
GO

执行程序

EXEC [Usp_UserLogin] @user_name='Test1',@user_email='Test1@gmail',@user_password='Test1@123',@user_number=2