我创建了一个VBA脚本,用于将表数据从服务器提取到Excel。但是要求每当“主列”以外的任何列发生更改时,都应该反映在数据库中
从sql表中获取数据的代码:
Sub ConnectSqlServer()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=servername;" & _
"Initial Catalog=dbname;" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
Set rs = conn.Execute("SELECT * FROM tablename;")
' To clear the excel sheet
ActiveSheet.Cells.ClearContents
' To get column names from SQL table
For i = 0 To rs.Fields.Count - 1
Sheet1.Range("A1").Offset(, i) = rs.Fields(i).Name
Next
' Check we have data.
If Not rs.EOF Then
' Transfer result.
Sheets(1).Range("A2").CopyFromRecordset rs
' Close the recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
' Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
检查主键的SQL查询:
SELECT
COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
WHERE
tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND tc.TABLE_NAME = '" & Sh.TableName & "'"
和VBA代码检查主键:
Function IsInPrimaryKey(name As String)
For Each pki In pk
If (pki = name) Then
IsInPrimaryKey = True
Exit Function
End If
Next pki
IsInPrimaryKey = False End Function
有没有办法实现上述要求?