简体   繁体   中英

SQL query getting Server name in triggers when using ASP.NET

I have a trigger set on SQL table for Audit Trail purpose. Here is the trigger code.

ALTER TRIGGER [dbo].[tri_bowzer_UPDATE] ON [dbo].[Bowzer] 
For Update 
AS
    INSERT Table_Audit(TableName, Action, UserName, ComputerName) 
       SELECT  
          'bowzer', 'U', suser_sname(), host_name()

It works fine and shows the username and the computer (client) name in Desktop applications. but in ASP.NET applications, I use a common SQL login so that database operations can be performed using this login. I understand that SQL Server is getting server machine name because of this ID. However, I want to capture the client machine name whenever a database operation is performed.

What changes can be made to get client machine name??

You need to tweak your connection string to specify the connectionstring property WSID (Workstation id) as below

string strconn = "data source=SQLSERVER;initial catalog = DBNAME ; uid=sa;pwd=password;  WSID=" + (System.Net.Dns.GetHostEntry(Request.ServerVariables["remote_addr"]).HostName);

and then you will get HOST_NAME() value as client machine name in your trigger

MSDN : http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx

您可以使用T-SQL SET CONTEXT_INFO设置客户端的IP地址,并使用CONTEXT_INFO函数在触发器中检索此数据。

This design is not really suitable for what you are trying to achieve. I'd consider adding updated by column in your database where you can store user id or machine name of a user who updated data.

This way you'll keep the trigger logic simple and avoid too many connections to your database that might degrade performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM