How to List Field's Name in table in Access Using SQL

后端 未结 14 1268
我在风中等你
我在风中等你 2020-12-09 17:15

Can you please let me know if it is possible to list all fields name in a MS Access table?

相关标签:
14条回答
  • 2020-12-09 17:45

    I would like to share this VBA solution, which I did not write, only slightly modified (changed the tableName to use 'SourceTable'). Once it is run you can query the table it creates. It takes advantage of hidden system tables.

    Sub GetField2Description()
    '************************************************* *********
    'Purpose: 1) Deletes and recreates a table (tblFields)
    ' 2) Queries table MSysObjects to return names of
    ' all tables in the database
    ' 3) Populates tblFields
    'Coded by: raskew
    'Inputs: From debug window:
    ' Call GetField2Description
    'Output: See tblFields
    '************************************************* *********
    Dim db As DAO.Database, td As TableDef
    Dim rs As Recordset, rs2 As Recordset
    Dim Test As String, NameHold As String
    Dim typehold As String, SizeHold As String
    Dim fielddescription As String, tName As String
    Dim n As Long, i As Long
    Dim fld As Field, strSQL As String
    n = 0
    Set db = CurrentDb
    ' Trap for any errors.
    On Error Resume Next
    tName = "tblFields"
    'Does table "tblFields" exist? If true, delete it;
    DoCmd.SetWarnings False
    DoCmd.DeleteObject acTable, "tblFields"
    DoCmd.SetWarnings True
    'End If
    'Create new tblTable
        db.Execute     "CREATE TABLE tblFields(Object TEXT (55), FieldName TEXT (55),     FieldType TEXT (20), FieldSize Long, FieldAttributes Long, FldDescription TEXT (20));"
    strSQL = "SELECT MSysObjects.Name, MSysObjects.Type From MsysObjects WHERE"
    strSQL = strSQL + "((MSysObjects.Type)=1)"
    strSQL = strSQL + "ORDER BY MSysObjects.Name;"
    Set rs = db.OpenRecordset(strSQL)
    If Not rs.BOF Then
    ' Get number of records in recordset
    rs.MoveLast
    n = rs.RecordCount
    rs.MoveFirst
    End If
    Set rs2 = db.OpenRecordset("tblFields")
    For i = 0 To n - 1
    fielddescription = " "
    Set td = db.TableDefs(i)
    'Skip over any MSys objects
    If Left(rs!Name, 4) <> "MSys" And Left(rs!Name, 1) <> "~" Then
    NameHold = rs!Name
    On Error Resume Next
    For Each fld In td.Fields
    tableName = fld.SourceTable
    
    fielddescription = fld.Name
    typehold = FieldType(fld.Type)
    SizeHold = fld.Size
    rs2.AddNew
    rs2!Object = tableName
    rs2!FieldName = fielddescription
    rs2!FieldType = typehold
    rs2!FieldSize = SizeHold
    rs2!FieldAttributes = fld.Attributes
    rs2!FldDescription = fld.Properties("description")
    rs2.Update
    Next fld
    Resume Next
    End If
    rs.MoveNext
    Next i
    rs.Close
    rs2.Close
    db.Close
    End Sub
    Function FieldType(intType As Integer) As String
    Select Case intType
    Case dbBoolean
    FieldType = "dbBoolean" '1
    Case dbByte
    FieldType = "dbByte" '2
    Case dbInteger
    FieldType = "dbInteger" '3
    Case dbLong
    FieldType = "dbLong" '4
    Case dbCurrency
    FieldType = "dbCurrency" '5
    Case dbSingle
    FieldType = "dbSingle" '6
    Case dbDouble
    FieldType = "dbDouble" '7
    Case dbDate
    FieldType = "dbDate" '8
    Case dbBinary
    FieldType = "dbBinary" '9
    Case dbText
    FieldType = "dbText" '10
    Case dbLongBinary
    FieldType = "dbLongBinary" '11
    Case dbMemo
    FieldType = "dbMemo" '12
    Case dbGUID
    FieldType = "dbGUID" '15
    End Select
    End Function
    
    0 讨论(0)
  • 2020-12-09 17:45

    select column_name from information_schema.columns where table_name='table'

    0 讨论(0)
  • 2020-12-09 17:46

    This is not SQL, but this question is the top Google result for someone like me who just needs to list out the field names needed for a query to select since Access does not support "* except foo, bar" for getting 99% of a table.

    Answer adapted from a social.msdn.com answer by Patrick Wood, Access MVP https://social.msdn.microsoft.com/Forums/office/en-US/1fe5546b-db3f-4e17-9bf8-04f4dee233b7/how-to-list-all-the-field-names-in-a-specified-table?forum=accessdev

    Change tablename to your name in the module. This Function should be at the global level:

    Function ListTdfFields()
        ' NOT doing DIMs, since then you must enable/attach ADODB or DAO
        ' Dim db As ADO.Database
        Set db = CurrentDb
        tablename = "tblProductLicense"  ' <=== YOUR TABLE NAME HERE
        Set tdf = db.TableDefs(tablename)
        For Each fld In tdf.Fields
            Debug.Print tablename; ".["; fld.Name; "]," ; 
            ' remove ending ; for 1 line per field
        Next
        Debug.Print ""
        Set tdf = Nothing
        Set db = Nothing
    End Function
    

    Then add a macro RunCode ListTdfFields() and run it. Output will be sent to the Immediate window of the VBA design view for the module.

    0 讨论(0)
  • 2020-12-09 17:48

    Give this a go...

        private void Button_OldDDLDump_Click(object sender, EventArgs e)
        {
            string _cnstr = "connectionstringhere";
            OleDbConnection _cn = new OleDbConnection(_cnstr);
            try
            {
                _cn.Open();
                System.Data.DataTable _dt = null;            
                try
                {
                    _dt = _cn.GetSchema("tables");
                    m_msghelper.AppendArray( DataTableHelper.DataTableToString(_dt) );                               
                }
                catch (Exception _ex)
                {
                    System.Diagnostics.Debug.WriteLine(_ex.ToString());
                }
                finally
                {
                    _dt.Dispose();
                }
            }
            catch (Exception _ex)
            {
                System.Diagnostics.Debug.WriteLine(_ex.ToString());
            }
            finally
            {
                _cn.Close();
            }
        }
    

    Helper method to dump the database structure to a string array here..

    public static class DataTableHelper
    {
        public static string[] DataTableToString( System.Data.DataTable dt )
        {
            List<string> _retval = new List<string>();
    
            foreach (System.Data.DataRow row in dt.Rows)
            {
                foreach (System.Data.DataColumn col in dt.Columns)
                {
                    _retval.Add( string.Format("{0} = {1}", col.ColumnName, row[col]) );
                }
                _retval.Add( "============================");
            }
            return _retval.ToArray();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 17:52

    Build query:

    SELECT Table_Name.*
    FROM Table_Name
    WHERE False;
    

    Export to Excel You will have each field name in one row without any data. If you select the row and copy, you can paste special>transpose and have them all in a single column.

    0 讨论(0)
  • 2020-12-09 17:53

    There are already some good answers but I decided to add my own twist. Hopefully, they are self-explanatory.

    Usage:

    • getFieldNames(TableName:="Table1",IncludeBrackets:=True,Delimiter:=vbNewLine,CopyToClipboard:=True)
    • getFieldNames(TableName:="Table1",IncludeBrackets:=True,CopyToClipboard:=True)
    • getFieldNames(TableName:="Table1",IncludeBrackets:=True)
    • getFieldNames(TableName:="Table1")

    I use this to build an array of field names:

    • Chr(34) & getFieldNames(TableName:="Table1",IncludeBrackets:=False, Delimiter:= Chr(34) & "," & Chr(34)) & Chr(34)

    Function getFieldNames(ByVal TableName As String, Optional ByVal IncludeBrackets As Boolean, Optional ByVal Delimiter As String = ", ", Optional ByVal CopyToClipboard As Boolean) As String
        Dim rs As DAO.Recordset
    
        On Error Resume Next
        Set rs = CurrentDb.OpenRecordset(TableName)
        On Error GoTo 0
    
        If rs Is Nothing Then Exit Function
    
        Dim results() As String
        ReDim results(rs.Fields.Count - 1)
    
        Dim n As Long
        For n = 0 To rs.Fields.Count - 1
            results(n) = rs.Fields(n).Name
        Next
        rs.Close
    
        Dim result As String
        If IncludeBrackets Then
            result = "[" & Join(results, "]" & Delimiter & "[") & "]"
        Else
            result = Join(results, Delimiter)
        End If
    
    
        If CopyToClipboard Then
            With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
                .SetText result
                .PutInClipboard
            End With
        End If
    
        getFieldNames = result
    End Function
    
    0 讨论(0)
提交回复
热议问题