最近的专案使用这个功能,开发时为程序使用了就定了一个系统帐号如sa,由于某些要求,此帐号不能被更改或是删除,但用户可以添加其它帐号。可以参考下面动画。
实现这样的功能,也许方法有很多种。Insus.NET使用了SQL的触发器(Trigger),在删除或是更新做了触发。
更新触发器,sa帐号不能被用户更新:
tri_Users_Update
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-03-03
-- Description: Disable update system account.
-- =============================================
CREATE TRIGGER [dbo].[tri_Users_Update]
ON [dbo].[Users]
FOR UPDATE
AS
BEGIN
IF @@ROWCOUNT = 0
RETURN
SET NOCOUNT ON;
DECLARE @UsersId INT,@Account NVARCHAR(100)
SELECT @UsersId = [UsersId] FROM deleted
SELECT @Account = [Account] FROM inserted
IF @UsersId = 1 and @Account <> N'sa'
BEGIN
RAISERROR(N'系统帐号,不能更新。',16,1)
ROLLBACK TRANSACTION
END
END
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-03-03
-- Description: Disable update system account.
-- =============================================
CREATE TRIGGER [dbo].[tri_Users_Update]
ON [dbo].[Users]
FOR UPDATE
AS
BEGIN
IF @@ROWCOUNT = 0
RETURN
SET NOCOUNT ON;
DECLARE @UsersId INT,@Account NVARCHAR(100)
SELECT @UsersId = [UsersId] FROM deleted
SELECT @Account = [Account] FROM inserted
IF @UsersId = 1 and @Account <> N'sa'
BEGIN
RAISERROR(N'系统帐号,不能更新。',16,1)
ROLLBACK TRANSACTION
END
END
删除触发器,sa帐号不能被用户删除。:
tri_Users_Delete
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-03-03
-- Description: Disable delete system account.
-- =============================================
ALTER TRIGGER [dbo].[tri_Users_Delete]
ON [dbo].[Users]
FOR DELETE
AS
BEGIN
IF @@ROWCOUNT = 0 RETURN
SET NOCOUNT ON;
DECLARE @UsersId INT,@Account NVARCHAR(100)
SELECT @UsersId = [UsersId],@Account = [Account] FROM deleted
IF @UsersId = 1 OR @Account = 'sa'
BEGIN
RAISERROR(N'系统帐号,不能删除。',16,1)
ROLLBACK TRANSACTION
END
END
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Insus.NET
-- Create date: 2012-03-03
-- Description: Disable delete system account.
-- =============================================
ALTER TRIGGER [dbo].[tri_Users_Delete]
ON [dbo].[Users]
FOR DELETE
AS
BEGIN
IF @@ROWCOUNT = 0 RETURN
SET NOCOUNT ON;
DECLARE @UsersId INT,@Account NVARCHAR(100)
SELECT @UsersId = [UsersId],@Account = [Account] FROM deleted
IF @UsersId = 1 OR @Account = 'sa'
BEGIN
RAISERROR(N'系统帐号,不能删除。',16,1)
ROLLBACK TRANSACTION
END
END