Hi @CEO ,
When the employee accesses his record page, he would be eligible to update ONLY the field for password
Maybe you could refer below:
drop table if exists testusers,pswlog
create table testusers
(userid int,
[password] varchar(20),
name varchar(20),
age int)
insert into testusers values
(1,'password1','Tom',20),
(2,'password2','Ann',19),
(3,'password3','Jim',22)
create table pswlog
(userid int,
oldpassword varchar(20),
newpassword varchar(20),
updatetime datetime)
CREATE TRIGGER psw_trigger
ON testusers
AFTER UPDATE
AS
IF ( UPDATE ([password]) )
BEGIN
insert into pswlog
select a.userid,c.password,a.password,getdate() from inserted a
inner join testusers b on a.userid=b.userid
inner join deleted c on a.userid=c.userid
END;
Perform some actions to make sure the employee could only update password column.
CREATE ROLE Employee
GO
CREATE USER EmployeeOne WITHOUT LOGIN;
GO
EXEC sp_addrolemember @membername = 'EmployeeOne', @rolename = 'Employee';
GO
GRANT SELECT ON dbo.testusers TO Employee;
GO
GRANT UPDATE ON dbo.testusers(PASSWORD) TO Employee;
GO
Then make a test.
EXECUTE AS USER = 'EmployeeOne';
GO
SELECT * FROM dbo.testusers WHERE userid=1;
GO
UPDATE testusers set password='password123' where userid=1
GO
Above is working. You could query this change in the table pswlog.
But if the user would like to update other column, it reports error.
update testusers set age=23 where userid=1
GO
Error:
Msg 230, Level 14, State 1, Line 20
The UPDATE permission was denied on the column 'age' of the object 'testusers', database 'testdb', schema 'dbo'.
After all, your requirement is a little complex and it may need more actions.Only TSQL statement is not enough.
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.