我有一个包含许多表的访问数据库。我正在寻找一个或多个表中可能存在或不存在的字段。我如何检查它是否存在? (当然没有查询每个表)
答案 0 :(得分:3)
如果您确实不想打开任何表,则解决方案是使用数据库对象的tabledefs
集合。每个tabledef
项都有自己的fields
集合,您可以浏览。它会给出类似的东西:
Public function findFieldInDatabase(p_myFieldName)
dim db as database, _
tb as tabledef, _
fd as field
set db = currentDb
for each tb in db.tabledefs
for each fd in tb.fields
if fd.name = p_myFieldName then
debug.print tb.name, fd.name
end if
next fd
next tb
set fd = nothing
set tb = nothing
set db = nothing
end function
可以很容易地调整此代码以接受可选的p_myTableName
作为参数,以将搜索限制为表/表范围。
答案 1 :(得分:2)
字段有一个架构:
Set cn = CurrentProject.Connection
SelectFieldName = "SomeFieldName"
'Get names of all tables that have a column = SelectFieldName '
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
答案 2 :(得分:2)
如果我想查看特定表中是否有特定列(在strSearch中标识),我会怎么做。
Public Sub search()
Dim db As Database
Dim strSearch As String
Dim strSQL As String
Dim rsResults As Recordset
Dim i As Integer
Dim cols As Integer
strSearch = "a3"
Set db = CurrentDb
strSQL = "select * from bar"
Set rsResults = db.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
If Not rsResults.BOF Then
rsResults.MoveFirst
End If
cols = rsResults.Fields.Count - 1 ' -1 because we start counting cols at 0
For i = 0 To cols
If rsResults(i).Name = strSearch Then
MsgBox "Found the seach string"
End If
Next
MsgBox "end of script"
End Sub
现在我知道你不想为每个表写一个。所以接下来要做的就是循环遍历所有表。您可以使用以下SQL
找到所有表的列表SELECT
name
FROM
MSysObjects
WHERE
(Left([Name],1)<>"~")
AND (Left([Name],4) <> "MSys")
AND ([Type] In (1, 4, 6))
将这两个部分连在一起,我将作为练习留给学生:)
答案 3 :(得分:0)
以下是使用VBScript访问MS Access中的表模式的方法:
TestData = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=c:\somefolder\YOURDB.mdb"
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open TestData
Set rs = Conn.OpenSchema(4)
do until Rs.eof
tn = RS("TABLE_NAME")
fn = RS("COLUMN_NAME")
' your script goes here
loop
答案 4 :(得分:0)
你走了:
Public Function fTableExists(ByVal vstrTable As String) As Boolean
Dim rs As ADODB.Recordset
Set rs = CurrentProject.Connection.OpenSchema( _
adschematables, Array(Empty, Empty, vstrTable))
fTableExists = Not rs.EOF
rs.Close
Set rs = Nothing
End Function
Public Function fColumnExists(ByVal vstrTable As String, _
ByVal vstrColumn As String) As Boolean
Dim rs As ADODB.Recordset
Set rs = CurrentProject.Connection.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, vstrTable, vstrColumn))
fColumnExists = Not rs.EOF
rs.Close
Set rs = Nothing
End Function
答案 5 :(得分:-1)
MSSQL 寻找ADDRESS1专栏: 从sysobjects中选择so.name so soid(从syscolumns sc中选择sc.id,其名称如'ADDRESS1')
ORACLE http://en.wikipedia.org/wiki/Oracle_metadata
Google会找到其他数据库的语法......
答案 6 :(得分:-1)
它是什么类型的数据库?如果是SQL Server,你可以试试这个:
SELECT * FROM sysobjects WHERE xtype = 'U' AND name = 'myTable'
但是因为它是你要找的专栏而不是桌子(感谢Brian),试试这个:
SELECT
DISTINCT
so.[name] AS 'Table',
sc.[name] AS 'Column'
FROM
syscolumns sc
JOIN
sysobjects so
ON
so.id = sc.id
WHERE
sc.[name] = 'myTable'