CLASSIC asp connecting to SQL Express Server 500 server error - database

Hey all i am trying to get a connection to my SQL server version 10.50.2500 in Classic ASP
My code in the .asp page is (including all connection strings I've tried using):
Set objConn = Server.CreateObject("ADODB.Connection")
Set objRS = Server.CreateObject("ADODB.Recordset")
'objConn.ConnectionString = "Provider={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;User ID=xxxx;Pwd=xxxx"
'objConn.ConnectionString = "Driver={SQL Server};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx;"
'objConn.ConnectionString = "Provider=SQLNCLI10;Server=xxx.xxx.xxx.xxx,1433;Database=JForm;Uid=xxxx;Pwd=xxxx;Persist Security Info=True"
'objConn.ConnectionString = "Provider=SQLNCLI;Server=.\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
objConn.ConnectionString = "Driver={SQL Server Native Client 10.0};Server=xxx.xxx.xxx.xxx\SQLEXPRESS;Database=JForm;Uid=xxxx;Pwd=xxxx"
strSQL = "UPDATE jURLS " & _
"SET rssFeedURL = 'http://www.xxxx.com/rss/" & rss & "'," & _
"csvURL = 'http://www.xxxx.com/csv/" & csv & "'," & _
"jFormName = '" & forname & "'," & _
"isActive = " & active & " " & _
"WHERE jFormName = '" & forname & "'"
objConn.open
objRS.Open strSQL, objConn, 1,3
'If Not objRS.EOF Then
'iterate through records here
'Else
'no records found
'End If
objRS.close
Set objRS=Nothing
objConn.close
Set objConn=Nothing
It seems to crash on the objConn.open. However, it only gives me a 500 - Internal server error. and not an error thats helpful!
Once i take the database code from the page and leave everything else, it works without the 500 - Internal server error being displayed.
What else can i try in order to get this to work?

you have an extra comma here :
"isActive = " & active & "," & _
change it to:
"isActive = " & active & " " & _
about the connection error, try debugging using the connection.errors collection
On Error Resume Next
objConn.open
for each errobj in objConn.Errors
Response.write errobj.Number & "<br />"
Response.write errobj.Description & "<br />"
next
On Error Goto 0

Try:
response.write(strSQL) <-- this will allow you to look at your current SQL statement and see if it makes sense.
set objRS = objConn.execute(strSQL)

Related

Excel VBA updating SQL Table - permissions issues

I am connecting to a SQL table via an Excel VBA script using using SQL Server vs Windows Authentication as we're creating a generic update application to be used by several different users. If I log into SQL Server Management Studio with the generic ID/pswd and SQL Server Authentication, I can successfully insert and delete rows. When I use the VBA script, I receive an error indicating that the INSERT or DELETE permission was denied. The VBA script works successfully against the same table in a different schema, but fails going against this schema. I am assuming it's something in the SQL environment, as it seems like it's forced to Windows Authentication regardless of how I make the connection. Any help would be greatly appreciated.
Updates:
Thanks for the responses. I hope this additional information helps. We are on SQL Server 15.04102.2, and I am using SQL Server Authentication with a generic application ID and PSWD that has update permissions (my individual windows account only has select permissions)
As I indicated in my initial post, if I execute this code against one test environment, the DELETE and INSERT work perfectly. When I execute it against a different environment, the connection is made, but I get the permissions error on the DELETE and INSERT. If I use the exact same credentials and use SQL Server Authentication to go directly to that environment, I can successfully execute the DELETE and INSERT statements.
Here is the error I receive on the DELETE statement. A similar error is received on the INSERT statement if I bypass the delete for a new add.
Error -2147217911 (The DELETE permission was denied on the object
‘BCG_CGS_DETAILS’, database ‘xxxxxxcustom’, schema ‘dbo’.) in
procedure Export CGS to SQL. sSQL = delete dbo.BCG_CGS_DETAILS where
[CGSNUM]= ‘CGS-xxxxx’ AND [PDPD_ID]= ‘xxxxx’ AND EFF_DT=’7/1/2021’
Here is the code I am executing.
Sub Export_CGS_to_SQL()
Dim cnn
Dim rst
Dim sSQL As String
Dim iRow As Integer
Dim sLINE, sCategory, sBCBSNC_Medical_Policy, sBCBSNC_Standard_Provisions As String
Dim sIn_Network_VALUE, sIn_Network_Type_of_payment, sIn_Network_Detail As String
Dim sOut_of_Network_VALUE, sOut_of_Network_Type_of_payment, sOut_of_Network_Detail As String
Dim sCustomized, sCGSNUM, sPDPD_ID, sEFF_DT As String
Dim lLastrow As Long
Dim sServer, sTable, sDatabase, sConnection As String
On Error GoTo errHandler
With Sheets("CGS Data")
sCGSNUM = .Cells(2, 12)
sPDPD_ID = .Cells(2, 13)
sEFF_DT = .Cells(2, 14)
If sCGSNUM = "" Or sPDPD_ID = "0" Or sEFF_DT = "" Then
MsgBox "One or more required fields is blank. Please make sure that the Product ID and Effective date are set correctly on the MISC tab, and that the CGS Number exists for row A06c on the Client Profile tab"
Exit Sub
End If
lLastrow = Cells(Rows.Count, 1).End(xlUp).Row
sServer = Worksheets("MACRO_DATA").Range("B6").Value
sTable = Worksheets("MACRO_DATA").Range("B7").Value
sDatabase = Worksheets("MACRO_DATA").Range("B8").Value
sConnection = Worksheets("MACRO_DATA").Range("F5").Value
'Create a new Connection object
Set cnn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
If cnn.State <> 1 Then
sSQL = "Provider=SQLOLEDB;Data Source=" & sServer & "; Initial Catalog=" & sDatabase & ";" & sConnection & "; Trusted_Connection=yes"
cnn.Open (sSQL)
End If
Set rst.ActiveConnection = cnn
sSQL = "delete " & sTable & " where [CGSNUM]= '" & sCGSNUM & "' AND [PDPD_ID]= '" & sPDPD_ID & "' AND EFF_DT= '" & sEFF_DT & "'"
cnn.Execute sSQL
For iRow = 2 To lLastrow
sLINE = .Cells(iRow, 1)
If sLINE <> "" Then
sCategory = .Cells(iRow, 2)
sBCBSNC_Medical_Policy = .Cells(iRow, 3)
sBCBSNC_Standard_Provisions = .Cells(iRow, 4)
sIn_Network_VALUE = .Cells(iRow, 5)
sIn_Network_Type_of_payment = .Cells(iRow, 6)
sIn_Network_Detail = .Cells(iRow, 7)
sOut_of_Network_VALUE = .Cells(iRow, 8)
sOut_of_Network_Type_of_payment = .Cells(iRow, 9)
sOut_of_Network_Detail = .Cells(iRow, 10)
sCustomized = .Cells(iRow, 11)
sCGSNUM = .Cells(iRow, 12)
sPDPD_ID = .Cells(iRow, 13)
sEFF_DT = .Cells(iRow, 14)
'insert row into sDatabase
sSQL = "insert into " & sTable & "([LINE],[Category],[BCBSNC Medical Policy],[BCBSNC Standard Provisions],[In-Network_VALUE]," _
& "[In-Network_Type of payment],[In-Network Detail],[Out-of-Network_VALUE],[Out-of-Network_Type of payment],[Out-of-Network_Detail]," _
& "[Customized],[CGSNUM],[PDPD_ID],[EFF_DT])" _
& "values ('" & sLINE & "', '" & sCategory & "', '" & sBCBSNC_Medical_Policy & "', '" & sBCBSNC_Standard_Provisions & "', '" _
& sIn_Network_VALUE & "', '" & sIn_Network_Type_of_payment & "', '" & sIn_Network_Detail & "', '" & sOut_of_Network_VALUE & "', '" _
& sOut_of_Network_Type_of_payment & "', '" & sOut_of_Network_Detail & "', '" & sCustomized & "', '" & sCGSNUM & "', '" _
& sPDPD_ID & "', '" & sEFF_DT & "')"
cnn.Execute sSQL
End If
Next iRow
MsgBox "CGS Data successfully exported to " & sTable, vbInformation
cnn.Close
Set cnn = Nothing
End With
Exit Sub
errHandler:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export CGS to SQL. sSQL = " & sSQL
cnn.Close
Set cnn = Nothing
End Sub

Writing to an SQL database with ASP Classic

Update - 2/14/21
Ok, this is where I'm at now. the code below works! Yay! However, there are no records in the database to read.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
'Query the tables I need
Set rs= conn.execute("SELECT * FROM [" & db_name & "].[" & db_schema & "].[" & db_tablename & "]")
do until rs.EOF
count = count + 1
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br>")
next
Response.Write("<br>")
rs.MoveNext
loop
Set conn = nothing
response.write "Records found = " & count
%>
''''
So with the part above is actually working again. I set out to add a record to the database with the code below. It seems to work as it does not cause an error. However, it is not adding the record though.
''''
<%
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital catalog=" & db_name & "; User ID=" & db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
If IsObject(conn) then
response.write "The connection is active!<br />"
if conn.State = 1 then
response.write "A connection is made, and is open.<br />"
end if
end if
sql="INSERT INTO " & db_name & "." & db_schema & "." & db_tablename & " (fname,lname,email,upassword)"
sql=sql & " VALUES "
sql=sql & "('John',"
sql=sql & "'Doe',"
sql=sql & "'JohnD#email.com',"
sql=sql & "'12345')"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else
Response.Write("<h3>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
%>
''''
This is where I have been stuck. It is not writing to the database. It just runs and nothing gets done. If I remove the resume next portion, it still works with no error but, still, no record being written cause the resume next. I have tried two different users to run the code. Both of which have read and write permission. Now what? I'll just keep trying until someone puts me out of my misery... lol!
Well, it seems a friend and I finally found out what was going on. The code actually works but, for some reason, the database's ID field is not auto-incrementing. So, in order to add a record, we had to first check to see how many records are in the DB then add 1 to the count to use for our new records id. Seems every solution leads to a new issue. That's programing...
Just in case any of that makes sense or even if it doesn't make sense, here the id's properties.
ID (PK, uniqueidentifier, not null)
db_server = "my_server"
db_name = "my_db-name"
db_username = "my_username"
db_userpassword = "my_password"
db_fieldname = "my_fieldname"
db_tablename = "my_tablename"
db_schema = "my_schema"
count = 0
'Establish a connection to the database
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open("Provider=SQLOLEDB; Data Source=" & db_server & "; Inital
catalog=" & db_name & "; intergaraded security = false ; User ID=" &
db_username & "; password=" & db_userpassword & ";")
'Test the connection to make sure it is available and it's open.
'If IsObject(conn) then
' response.write "The connection is active!<br />"
' if conn.State = 1 then
' response.write "A connection is made, and is open.<br />"
' end if
'end if
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
on error resume next
do until rs.EOF
for each x in rs.Fields
count = x.value
'response.write x.value & "<br>"
next
rs.MoveNext
loop
'conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>id: " & err.description)
else
'Response.Write("<h3>" & count & " record in db</h3>")
end if
'conn.close
Set rs= conn.execute("Select top 1 id from " & db_name & "." & db_schema & "." & db_tablename & " order by id desc")
sql=sql & " VALUES "
sql=sql & "(" & cstr(count + 1) & ","
sql=sql & "'John',"
sql=sql & "'Doe',"
sql=sql & "'user#website.com',"
sql=sql & "'1234abcd')"
'response.write sql & "<br>"
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("<br>insert: " & err.description)
else
'Response.Write("<br>" & recaffected & " record added</h3>")
end if
conn.close
Set conn = nothing
I left all the error checking in there but, it is all commented out. I hope this is the last time I have to come back to this. Goodluck!

Automation Error when executing SQL Server Script in Excel VBA

I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute

Query will not update SQL Server

In the below code, my second query will not insert into the SQL database, but the first one will update. I can copy the query (from the msgbox i added for testing) and paste it in SQL Server Management Studio, and it will execute fine. I also do not get any error messages back from SQL, though i'm not sure if that code is correct (it was copied + pasted from another source). Also, can i simplify the code to pass both queries at the same time?
Dim Conn As New System.Data.SqlClient.SqlConnection 'sql server datastream connection
Dim Cmd As New System.Data.SqlClient.SqlCommand 'sql command vars
Dim SqlQuery As String 'string var used to hold various SQL queries
Dim data As System.Data.SqlClient.SqlDataReader 'datareader object variable
Dim MVDataset As New DataSet
Dim MVDatatable As DataTable
Dim MVDatarow As DataRow
Private Sub MVUpdateButton_Click(sender As Object, e As EventArgs) Handles MVUpdateButton.Click
vbyn = MsgBox("Are you sure you want to update Tally Sheet Master Variables?" & vbCrLf & vbCrLf & "Changes to these variables will change the functionality of the Tally Sheet!", vbYesNo, )
Try
Select Case vbyn
Case vbNo
GoTo MVTableUpdateBypass
Case vbYes
'get new data from textboxes
Vers = TextBox1.Text
If TextBox2.Text = True Then
Testing = 1
Else
Testing = 0
End If
FlatFeeCharge = TextBox3.Text
PrepricingCharge = TextBox4.Text
SendMailAcct = TextBox5.Text
SendMailPW = TextBox6.Text
TestingEmail = TextBox7.Text
PrePricingEmail = TextBox8.Text
ImperataEmail = TextBox9.Text
'update existing active row to mark inactive
SqlQuery = "Update MasterVars set Active = 0 where PKEY = " & PKEY & ";"
MsgBox(SqlQuery)
If Conn.State = ConnectionState.Closed Then
Conn.ConnectionString = "Data Source=SQL01;Initial Catalog=TallySheet;Integrated Security=SSPI;"
End If
Conn.Open()
Dim MVDataAdapter As New SqlDataAdapter(SqlQuery, Conn)
Dim MVUpdateCommand As SqlCommand
MVUpdateCommand = New SqlCommand(SqlQuery)
MVDataAdapter.UpdateCommand = MVUpdateCommand
'insert new active row
SqlQuery = "Insert into MasterVars (Vers, Testing, FlatFeeCharge, PrePricingCharge, SendMailAcct, SendMailPW, TestingEmail, PrePricingEmail, ImperataEmail, DTS, UserName, Active) Values (" & "'" & Vers & "', " & Testing & ", '" & FlatFeeCharge & "'" & ", '" & PrepricingCharge & "'" & ", '" & SendMailAcct & "'" & ", '" & SendMailPW & "'" & ", '" & TestingEmail & "'" & ", '" & PrePricingEmail & "'" & ", '" & ImperataEmail & "'" & ", '" & Date.Now & "'," & "'QGDOMAIN\" & Environment.UserName & "'," & 1 & ");"
MsgBox(SqlQuery)
Dim MVInsertCommand As SqlCommand
MVInsertCommand = New SqlCommand(SqlQuery)
MVDataAdapter.InsertCommand = MVInsertCommand
MVDataAdapter.Fill(MVDataset, "MasterVars")
End Select
Catch ex As SqlException
Dim i As Integer
Dim errormessages As String
errormessages = ""
For i = 0 To ex.Errors.Count - 1
errormessages = errormessages & " " & ("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
Console.WriteLine(errorMessages.ToString())
End Try
'reload form with updated variables
Conn.Close()
Conn.Dispose()
MVTableUpdateBypass:
End Sub
The Fill method of the SqlDataAdapter executes the SelectCommand not the UpdateCommand or the InsertCommand. In any case these two commands (and the DeleteCommand) are executed when you call the Update method of the adapter.
Moreover the Update method runs the commands looking for rows changed/added/deleted in the DataTable/DataSet retrieved by the SelectCommand and works only for those rows.
But you don't need an SqlDataAdapter to execute your two queries. You should simply construct an SqlCommand with both texts separated by a semicolon and call ExecuteNonQuery
SqlQuery = "Update MasterVars set Active = 0 where PKEY = #key;" & _
"Insert into MasterVars (Vers, Testing, .....) VALUES (#p1, #o2, ....)"
Using Conn = New SqlConnection("Data Source=SQL01;......")
Using cmd = New SqlCommand(SqlQuery, Conn)
Conn.Open()
cmd.Parameters.Add("#key", SqlDbType.Int).Value = PKEY
cmd.Parameters.Add("#p1", SqlDbType.NVarChar).Value = vers
cmd.Parameters.Add("#p2", SqlDbType.Int).Value = testing
... and so on with other parameters ....
cmd.ExecuteNonQuery()
End Using
End Using
In this incomplete example (too many parameters to write down) I have concatenated the two sql texts in a single string and prepared it with parameter placeholders. Then I build the parameter collection with the exact datatypes required by your table and finally call ExecuteNonQuery to run everything on the database side.
Notice that is not needed to keep global objects like the connection or the command. It is always better to create a local variable, use and destroy it when done. In particular disposable objects like the connection and the command should always created in a Using block

Changing SQL connection information for DSN-less Access frontend

I've got a mission-critical Access 2003 database that changed from a local MDB, to an MDB frontend with the backend on MS SQL Server 2005, using the Microsoft SQL Server Database Migration Assistant (SSMA) software.
Now, I need to permanently change the server that the tables are linked to from an IP address (which is changing soon) to a hostname pointing to the same server. The server itself is not changing, just the connection string.
It's a DSN-less connection, so the ODBC info is contained within the Access MDB file. If I try to refresh the table links within Access, it prompts me for a DSN (which I don't want to use).
I've done some Googling, and I've found several scraps of code to have it update itself each time the program launches. But, I'm worried that that could potentially introduce problems or delays for the users. Is that my best option, or is there some trick to permanently change the connection string stored within the MDB?
The following code has served me well for years:
Function LinkTable(DbName As String, SrcTblName As String, _
Optional TblName As String = "", _
Optional ServerName As String = DEFAULT_SERVER_NAME, _
Optional DbFormat As String = "ODBC") As Boolean
Dim db As dao.Database
Dim TName As String, td As TableDef
On Error GoTo Err_LinkTable
If Len(TblName) = 0 Then
TName = SrcTblName
Else
TName = TblName
End If
'Do not overwrite local tables.'
If DCount("*", "msysObjects", "Type=1 AND Name=" & Qt(TName)) > 0 Then
MsgBox "There is already a local table named " & TName
Exit Function
End If
Set db = CurrentDb
'Drop any linked tables with this name'
If DCount("*", "msysObjects", "Type In (4,6,8) AND Name=" & Qt(TName)) > 0 Then
db.TableDefs.Delete TName
End If
With db
Set td = .CreateTableDef(TName)
td.Connect = BuildConnectString(DbFormat, ServerName, DbName)
td.SourceTableName = SrcTblName
.TableDefs.Append td
.TableDefs.Refresh
LinkTable = True
End With
Exit_LinkTable:
Exit Function
Err_LinkTable:
'Replace following line with call to error logging function'
MsgBox Err.Description
Resume Exit_LinkTable
End Function
Private Function BuildConnectString(DbFormat As String, _
ServerName As String, _
DbName As String, _
Optional SQLServerLogin As String = "", _
Optional SQLServerPassword As String = "") As String
Select Case DbFormat
Case "NativeClient10"
BuildConnectString = "ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=" & ServerName & ";" & _
"Database=" & DbName & ";"
If Len(SQLServerLogin) > 0 Then
BuildConnectString = BuildConnectString & _
"Uid=" & SQLServerLogin & ";" & _
"Pwd=" & SQLServerPassword & ";"
Else
BuildConnectString = BuildConnectString & _
"Trusted_Connection=Yes;"
End If
Case "ADO"
If Len(ServerName) = 0 Then
BuildConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & DbName & ";"
Else
BuildConnectString = "Provider=sqloledb;" & _
"Server=" & ServerName & ";" & _
"Database=" & DbName & ";"
If Len(SQLServerLogin) > 0 Then
BuildConnectString = BuildConnectString & _
"UserID=" & SQLServerLogin & ";" & _
"Password=" & SQLServerPassword & ";"
Else
BuildConnectString = BuildConnectString & _
"Integrated Security=SSPI;"
End If
End If
Case "ODBC"
BuildConnectString = "ODBC;" & _
"Driver={SQL Server};" & _
"Server=" & ServerName & ";" & _
"Database=" & DbName & ";"
If Len(SQLServerLogin) > 0 Then
BuildConnectString = BuildConnectString & _
"Uid=" & SQLServerLogin & ";" & _
"Pwd=" & SQLServerPassword & ";"
Else
BuildConnectString = BuildConnectString & _
"Trusted_Connection=Yes;"
End If
Case "MDB"
BuildConnectString = ";Database=" & DbName
End Select
End Function
Function Qt(Text As Variant) As String
Const QtMark As String = """"
If IsNull(Text) Or IsEmpty(Text) Then
Qt = "Null"
Else
Qt = QtMark & Replace(Text, QtMark, """""") & QtMark
End If
End Function
You can use VBA to alter the .Connect properties for your linked TableDef s.
See this sample from the Immediate window. (I used Replace() simply to split up that long line.)
? Replace(CurrentDb.TableDefs("remote_table").Connect, ";", ";" & vbCrLf)
ODBC;
DRIVER=SQL Server Native Client 10.0;
SERVER=HP64\SQLEXPRESS;
Trusted_Connection=Yes;
APP=Microsoft Office 2003;
WSID=WIN732B;
DATABASE=testbed;
So I could build a new string with a different SERVER, and assign the new string to the TableDef .Connect property.
If this is intended to be a permanent change you should only need to do it one time, not every time you open the database.
When I've done similar connection changes, it has been between different servers. So I deleted the TableDef and re-created it anew, to make sure Access didn't keep any cached meta information about that connection which would now be out of date. However, in your case, you're dealing with the same physical server, just referencing it by name instead of IP. I doubt the cached information would be a concern for you.

Resources