权限管理----用户与角色关系
权限管理,必涉及到用户与角色关系。
下面的做法,是对某一个用户授权拥有某个角色。一个用户可拥有多个角色。
建立一张表[UsersRole]其中有三个字段,[UsersId]注册用户ID,[RoleId]角色表的主ID,还有一个字段[IsEnable]数据类型为BIT是记录用户是否拥有此角色。
表的结构如下:
代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UsersRole](
[UsersId] [int] NOT NULL,
[RoleId] [smallint] NOT NULL,
[IsEnable] [bit] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[UsersRole] WITH CHECK ADD CONSTRAINT [FK_UsersRole_Role] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([RoleId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersRole] CHECK CONSTRAINT [FK_UsersRole_Role]
GO
ALTER TABLE [dbo].[UsersRole] WITH CHECK ADD CONSTRAINT [FK_UsersRole_Users] FOREIGN KEY([UsersId])
REFERENCES [dbo].[Users] ([UsersId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersRole] CHECK CONSTRAINT [FK_UsersRole_Users]
GO
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UsersRole](
[UsersId] [int] NOT NULL,
[RoleId] [smallint] NOT NULL,
[IsEnable] [bit] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[UsersRole] WITH CHECK ADD CONSTRAINT [FK_UsersRole_Role] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Role] ([RoleId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersRole] CHECK CONSTRAINT [FK_UsersRole_Role]
GO
ALTER TABLE [dbo].[UsersRole] WITH CHECK ADD CONSTRAINT [FK_UsersRole_Users] FOREIGN KEY([UsersId])
REFERENCES [dbo].[Users] ([UsersId])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[UsersRole] CHECK CONSTRAINT [FK_UsersRole_Users]
GO
接下来,写分配角色存储过程:
代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_UsersRole_AssignRole]
(
@UsersId int,
@RoleId smallint,
@IsEnable bit
)
AS
BEGIN TRANSACTION
DECLARE @err int
--判断[UsersRole]表中,此用户与此角色是否存在记录
IF (SELECT count(*) FROM [UsersRole] WHERE [UsersId] = @UsersId AND [RoleId] = @RoleId ) > 0
BEGIN
--如果存在,作更新动作
UPDATE [UsersRole] SET [IsEnable]= @IsEnable WHERE [UsersId] = @UsersId AND [RoleId] = @RoleId
SET @err=@@ERROR
IF @err<>0
ROLLBACK TRANSACTION
END
ELSE
BEGIN
--如果不存在,做插入记录动作
INSERT INTO [UsersRole] ([UsersId] ,[RoleId],[IsEnable] ) VALUES (@UsersId ,@RoleId ,@IsEnable)
SET @err=@@ERROR
IF @err<>0
ROLLBACK TRANSACTION
END
COMMIT TRANSACTION
GO
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_UsersRole_AssignRole]
(
@UsersId int,
@RoleId smallint,
@IsEnable bit
)
AS
BEGIN TRANSACTION
DECLARE @err int
--判断[UsersRole]表中,此用户与此角色是否存在记录
IF (SELECT count(*) FROM [UsersRole] WHERE [UsersId] = @UsersId AND [RoleId] = @RoleId ) > 0
BEGIN
--如果存在,作更新动作
UPDATE [UsersRole] SET [IsEnable]= @IsEnable WHERE [UsersId] = @UsersId AND [RoleId] = @RoleId
SET @err=@@ERROR
IF @err<>0
ROLLBACK TRANSACTION
END
ELSE
BEGIN
--如果不存在,做插入记录动作
INSERT INTO [UsersRole] ([UsersId] ,[RoleId],[IsEnable] ) VALUES (@UsersId ,@RoleId ,@IsEnable)
SET @err=@@ERROR
IF @err<>0
ROLLBACK TRANSACTION
END
COMMIT TRANSACTION
GO
在asp.net的介面,太概如下: