0
我有一個數據庫,其中兩個模式由相同的一組表組成。我使用VBA中的連接字符串連接到數據庫,並使用VBA創建插入腳本。但是,由於有兩個具有相同表格的模式,我的代碼正在爲兩個模式中的每個表格返回插入腳本。我需要知道如何指定使用哪個模式。下面是我使用的代碼..如何在連接字符串中指定模式名稱VBA
子GenerateStandardBusinessRule_UpdateSQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim rsSys As Recordset
Dim ServName As String
Dim dbName As String
Dim dbType As String
Dim TableName As String
Dim InstName As String
Dim wrk As String
Dim sUpdStart As String
Dim sUpdEnd As String
Dim i
Dim sSQL As String
Dim sUser As String
Dim sPW As String
Dim sField As String
Dim n As Integer
'Instantiate variables
ServName = Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("A2").Value
dbName = Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("B2").Value
InstName = Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("C2").Value
TableName = Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("D2").Value
dbType = Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("E2").Value
wrk = "UPDATE " & InstName & "." & TableName & vbCrLf & "SET" & Chr(10)
If dbType = "Varchar" Then
sUpdStart = "= NULLIF(LTRIM(RTRIM(": sUpdEnd = ")),'')"
Else
sUpdStart = "=CAST(": sUpdEnd = " as date)"
End If
'Get Data type info
sSQL = "SELECT Column_Name " & _
"FROM Information_Schema.Columns " & _
"WHERE Table_Name = " & Chr(39) & TableName & Chr(39) & " " & _
"AND Data_Type = " & Chr(39) & dbType & Chr(39) & ""
'Set db Connection and open Recordset
Set cn = New ADODB.Connection
cn.Open "Provider=SQLOLEDB;Data Source=" & ServName & " ; Initial Catalog=" & dbName & "; User ID=ETLUser; Password=xxxxxxxx;"
Set rs = New ADODB.Recordset
rs.Open sSQL, cn, adOpenKeyset, adLockOptimistic
'Loop through recordset and contruct SQL Update statement
If Not rs.BOF Then
rs.MoveLast
i = rs.RecordCount
n = 1
rs.MoveFirst
Do Until rs.EOF
sField = rs("Column_Name")
If n < i Then
wrk = wrk & vbTab & sField & sUpdStart & sField & sUpdEnd & "," & Chr(10)
Else
wrk = wrk & vbTab & sField & sUpdStart & sField & sUpdEnd
End If
rs.MoveNext
n = n + 1
Loop
End If
'Update Excel Spreadsheet
Workbooks("BusinessRules_UpdatesBuilder.xlsm").Sheets("BuildStatement").Range("F3").Value = wrk
末次
是不是就像'DB.SCHEMA'? –
[您之前詢問過嗎?](http://stackoverflow.com/questions/3282665/possible-to-set-default-schema-from-connection-string) – Kyle
正如在下面發佈的答案中所述:您是連接到服務器,而不是**服務器上的模式或數據庫。您可以在連接字符串中指定默認數據庫以覆蓋爲SQL Server上的用戶指定的任何內容。但即使這樣可以在查詢中重寫(非常像架構)。在更新VBA之前,您應該學習和了解有關SQL的知識。之後,你會得出結論:你必須更新這一行:'wrk =「UPDATE」&InstName&「。」 &TableName&vbCrLf&「SET」&Chr(10)',這樣你就可以得到'UPDATE DataBaseName.SchemaName.TableName'。 – Ralph