具有输入输出范围标识的存储过程

时间:2018-09-12 05:21:38

标签: sql sql-server tsql

我有两个表,即User和UserRole,我想在其中通过存储过程将值传递给下表。我需要帮助,以确保用户只有一个角色(即用户或管理员)的方式创建一个可以插入到两个表中的过程。

插入第二个表的Id参数必须是用户表的ID。 请建议我。

CREATE TABLE [dbo].[User](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NULL,
    [Username] [nvarchar](50) NULL,
    [Password] [nvarchar](50) NULL,
)
CREATE TABLE [dbo].[UserRole](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [int] Foreign Key References User(ID)NOT NULL,
    [Role] [nvarchar](50) NULL
)

CREATE PROCEDURE [dbo].[AddUserRole]
    @Name      VARCHAR(50),
    @Username DATETIME,
    @Password      INT,
    @Role NVARCHAR(50),
     @Id INT OUT
AS
BEGIN
    SET NOCOUNT ON;

    INSERT INTO [WH].[dbo].[User]
                (
                Name,
                Username,
                Password
                )
    VALUES  
                (
                @ Name, 
                @Username,
                 @Password
                );

    SET @ Id = SCOPE_IDENTITY();

INSERT INTO [WH].[dbo].[UserRole]
                (
                UserId,
                Role
                )
    VALUES  
                (
                @Id, 
                @ Role
                );
END;

2 个答案:

答案 0 :(得分:2)

使用输出方法,详细信息here

尝试类似的东西

DECLARE @MyTableVar table( Id int);  

INSERT INTO [WH].[dbo].[User] (Name, Username, Password)
OUTPUT INSERTED.Id  INTO @MyTableVar
VALUES  (@Name, @Username, @Password);


INSERT INTO [WH].[dbo].[UserRole] (UserId, Role )
SELECT Id, @Role FROM @MyTableVar;

答案 1 :(得分:0)

enter image description here现在可以正常工作了!

        CREATE TABLE [dbo].[TempUser](
        [Id] [int] IDENTITY(1,1) NOT NULL Primary key,
        [Name] [nvarchar](50) NULL,
        [Username] [nvarchar](50) NULL,
        [Password] [nvarchar](50) NULL,
    )
    CREATE TABLE [dbo].[TempUserRole](
        [Id] [int] IDENTITY(1,1) NOT NULL,
        [UserId] [int] Foreign Key References TempUser(ID)NOT NULL,
        [Role] [nvarchar](50) NULL
    )
    --ALTER TABLE TempAddUserRole DROP CONSTRAINT FK__TempUserR__UserI__503293D2;



EXEC TempAddUserRole 'Gulshan','12 sep 2018','1','Admin'
EXEC TempAddUserRole 'Gulshan','12 sep 2018','1','Admin',


ALTER PROCEDURE [dbo].[TempAddUserRole]
    @Name      VARCHAR(50),
    @Username DATETIME,
    @Password      INT,
    @Role NVARCHAR(50)

AS
BEGIN
    SET NOCOUNT ON;

     declare @Id INT 


    INSERT INTO [TempUser]
                (
                Name,
                Username,
                Password
                )
    VALUES  
                (
                @Name, 
                @Username,
                 @Password
                );

    SET @Id = SCOPE_IDENTITY();

INSERT INTO [TempUserRole]
                (
                UserId,
                Role
                )
    VALUES  
                (
                @Id, 
                @Role
                );
END;