For various reasons you may need to audit some activities on certain tables.Usually you can use triggers for this.Sometimes you may want to know the system from which data are added or the user who added data.In these cases, you can use two functions host_name() and user_name()
Host_name()
This function is used to return the name of the system from which the code is executed. The following will return your system name
select host_name()
user_name()
This function is used to return the name of the user identified by a userid. The following will return the user name for the particular userid.
select user_name(1)
If you omit userid parameter by default current user of the session is considered and it returns the name of the user who is currently connected to the session
select user_name()
Now you can use these functions to know the user who adds data to a table as well as the system in which data come from. Consider the follwoing table that has two columns wirh default values of these function
declare @test table
(
productid varchar(10), amount decimal(12,2),
system_name varchar(100) default host_name(),
username varchar(100) default user_name()
)
insert into @test(productid,amount)
select 'P001',7234.45 union all
select 'P002',2000.10
select * from @test
The result is
productid amount system_name username
---------- --------------------------------------- ----------- ----------
P001 7234.45 SYS100 dbo
P002 2000.10 SYS100 dbo