简体   繁体   中英

Insert records into SQL Server database from user defined table type using stored procedure

Scenario

I have this Datatable which I'm getting from when user assign role to other user:

在此处输入图片说明

In the above table, I assign a new role to user mushtaq and through below procedure I want to insert it in my database.

ALTER PROCEDURE [dbo].[SP_ROLE_ASSIGNMENT_ASSIGN_ROLES_TO_USER]
    @RoleAssignmentDT _ROLEASSIGNMENTSCHEMA ReadOnly
AS
BEGIN TRY
BEGIN TRANSACTION
    IF EXISTS (SELECT Role_ID 
               FROM Role_Assignment RA 
               INNER JOIN @RoleAssignmentDT t ON t._Role_ID = Ra.Role_ID 
                                              AND RA.Username = t._Username)
    BEGIN
        UPDATE Role_Assignment
        SET Role_Assign = 0, 
            Modified_By_ID = t._Modified_By_ID, 
            Modified_Date = GETDATE()
        FROM @RoleAssignmentDT t
        WHERE Role_Assignment.Role_ID <> t._Role_ID 
          AND Role_Assignment.Username = t._Username
          AND (t._Role_Assign = 1 AND Role_Assignment.Role_Assign = 1)

        UPDATE Role_Assignment
        SET Role_Assign = t._Role_Assign, 
            Modified_By_ID = t._Modified_By_ID, 
            Modified_Date = GETDATE()
        FROM @RoleAssignmentDT t
        WHERE Role_Assignment.Role_ID = t._Role_ID 
          AND Role_Assignment.Username = t._Username
    END
    ELSE
    BEGIN
        INSERT INTO Role_Assignment (Role_ID, Username, Role_Assign, Prepared_By_ID, Prepared_Date)
            SELECT
                t._Role_ID, t._Username, t._Role_Assign, t._Prepared_By_ID, GETDATE()  
            FROM 
                @RoleAssignmentDT t
    END

    COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
--RAISERROR('No Record Inserted, Contact to administrator',16,1)
    DECLARE @Msg NVARCHAR(MAX)  
    SELECT @Msg=ERROR_MESSAGE() 
    RAISERROR('Error Occured: %s', 20, 101,@msg) WITH LOG
END CATCH

Below is my SQL Role_Assignment table's schema

在此处输入图片说明

Now, when I assign new roles to other user above procedure only updates user ahmer . Because when my procedure gets the datatable my IF condition run and it finds user ahmer and updates it.

What I want

I want the stored procedure to check and update only those users who exist in the SQL Server table Role_Assignment ; if they don't exist, then insert them first.

I think I provide brief information about my current problem. Please help me what modification I need to do in my store procedure so it first check weather user exists or not. Those who not exists before then insert them and update other those who exists.

Try the following in place of your t-sql code in the stored procedure

 MERGE Role_Assignment ra
    USING @RoleAssignmentDT t
    ON Role_Assignment.Username = t._Username
    WHEN MATCHED AND
       Role_Assignment.Role_ID <> t._Role_ID 
    and (t._Role_Assign = 1 and Ra.Role_Assign = 1) THEN
       UPDATE
        Set Role_Assign = 0, Modified_By_ID = t._Modified_By_ID, Modified_Date = GETDATE()
        From @RoleAssignmentDT
    WHEN MATCHED AND
    Role_Assignment.Role_ID = t._Role_ID  THEN
      UPDATE
        Set Role_Assign = t._Role_Assign, Modified_By_ID = t._Modified_By_ID, Modified_Date = GETDATE()
        From @RoleAssignmentDT
    WHEN NOT MATCHED BY TARGET THEN
      Insert (Role_ID,Username,Role_Assign,Prepared_By_ID,Prepared_Date)
        VALUES (t._Role_ID, t._Username, t._Role_Assign, t._Prepared_By_ID, GETDATE());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM