When a recent project uses this function, a system account, such as sa, is set for the program during development. Due to certain requirements, this account cannot be changed or deleted, but you can add other accounts. You can refer to the following animation.
There may be many ways to implement this function. Insus. NET uses the SQL Trigger and triggers deletion or update.
Update trigger. The sa account cannot be updated by the user:
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' SYSTEM account, which cannot be updated. ', 16,1)
ROLLBACK TRANSACTION
END
END
The sa account cannot be deleted. :
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' SYSTEM account, cannot be deleted. ', 16,1)
ROLLBACK TRANSACTION
END
END
From Insus. NET