R - Manual RODBC Windows Authentication

cdeterman picture cdeterman · Feb 16, 2017 · Viewed 7.4k times · Source

When using RODBC to connect to Microsoft SQL Server I know I can do the following:

con <- odbcDriverConnect(connection="driver={SQL Server};server=servername;database=dbname;trusted_connection=yes;")

However, that limits me to using the windows authentication for my current windows username. Our processes often require using different log in credentials for different processes. If I need to use a different log in credential using windows authentication is there a way to do that manually? For example, the following fails for me.

con <- odbcDriverConnect(connection="driver={SQL Server};server=servername;database=dbname;uid=domain\\username;pwd=passwd;")

I thought I could use the format domain\\username but it never works and I just keep getting an error like this:

Warning messages: 1: In odbcDriverConnect(connection = "driver={SQL Server};server=servername;database=dbname;uid=domain\username;pwd=passwd") : [RODBC] ERROR: state 28000, code 18456, message [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'domain\username'

My concern is that this is impossible given the answer I found in this question.

This is rather frustrating because I can use an arbitrary user if I use RSQLServer.

con <- dbConnect(RSQLServer::SQLServer(), "servername", database = "dbname",
                    properties = list(user = "username", password = "passwd",
                                      useNTLMv2=TRUE, domain = "domain")
                    )

I would prefer to use RODBC in this situation though because a lot of previously written code depends upon the RODBC specific functions (e.g. sqlQuery) instead of the DBI functions.

Answer