How to use system username directly in MS Access query?

前端 未结 4 1500
萌比男神i
萌比男神i 2020-11-28 15:57

I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a fo

相关标签:
4条回答
  • 2020-11-28 16:36

    You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)

    0 讨论(0)
  • 2020-11-28 16:39

    You need to create a VBA function that returns the username, and then use the function in the query.

    Public Function GetUserName() As String
        ' GetUserName = Environ("USERNAME")
        ' Better method, see comment by HansUp
        GetUserName = CreateObject("WScript.Network").UserName
    End Function
    

    and

    SELECT foo FROM bar WHERE myUserName = GetUserName();
    
    0 讨论(0)
  • 2020-11-28 16:41

    Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.

    SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];
    
    0 讨论(0)
  • 2020-11-28 16:50

    My solution kept all the work in VB.
    I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.

    The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.

    If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.

    MyName = Environ("username")
    
    sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
    
    Forms![Main Form].RecordSource = sqlstr
    
    0 讨论(0)
提交回复
热议问题