插入/删除多对多关系中的示例

时间:2015-02-02 10:27:48

标签: sql-server many-to-many

我有三个表,用户,角色和一个UserRoles连接点。

Users       UserRoles         Roles
=======     =============     =========
UserId      UserId            RoleId
Username    RoleId            Role
Firstname   Date

我的表格加入如下:

Users.UserId -> UserRoles.UserId
Roles.RoleId -> UserRoles.RoleId 

基本上,我正在寻找的是一个简单的例子,显示:

  1. 如何在UserRoles中插入具有特定角色的特定用户名的UserId和RoleId。
  2. 删除特定用户名的角色
  3. 我设法在Roles上为特定的用户名进行简单的选择,如下所示:

    SELECT 
        dbo.Roles.Role 
    FROM dbo.Roles 
    INNER JOIN dbo.UserRoles 
        ON dbo.Roles.RoleId = dbo.UserRoles.RoleId 
    INNER JOIN dbo.Users 
        ON dbo.UserRoles.UserId = dbo.Users.UserId 
    WHERE (Username = @Username)
    

2 个答案:

答案 0 :(得分:3)

要在UserRoles中插入具有特定角色的特定用户名的UserId和RoleId,您需要重新设计表,以便User表具有Roles表的外键,如下所示:

Users       UserRoles         Roles
=======     =============     =========
UserId      UserId            RoleId
Username    RoleId            Role
Firstname   Date
RoleId

然后插入如下:

insert into dbo.UserRoles (UserId, RoleId, [Date])
select
    u.UserId,
    r.RoleId,
    getdate() as [Date]
from dbo.Users u
inner join dbo.Roles r
   on r.RoleId = u.RoleId
   and u.Username = @Username

使用上述架构删除特定用户名的角色:

delete r
from dbo.Roles r
inner join dbo.User u
   on r.RoleId = u.Roleid
where u.Username = @Username

编辑:@sidux建议的另一个解决方案

DELETE ur 
FROM dbo.UserRoles ur 
JOIN dbo.Roles r 
    ON r.RoleId = ur.RoleId 
INNER JOIN dbo.Users u 
    ON ur.UserId = u.UserId 
WHERE (Username = @Username);

答案 1 :(得分:0)

你可以使用Merge并在proc中写下所有内容。别忘了测试并在这里给出错误信息。

我正在使用@Flg,因为您可能还需要更新声明。在这种情况下,它会有所帮助。

Declare @Flg char(1)='D' -- D/I/U

Declare @Username varchar(50)

Merge into UserRoles  as trg
using(Select
    u.UserId,
    r.RoleId,
    getdate() as [Date]
from dbo.Users u
inner join dbo.Roles r
   on r.RoleId = u.RoleId
   and u.Username = @Username)src
on trg.UserId=src.UserId and trg.RoleId=src.RoleId
when not matched and @Flg='I' THen
insert values(src.UserId,src.RoleId,[Date])
When matched and  @Flg='D' THen
Delete ;