在MS Access中绘制动态定义的字段

时间:2010-02-04 11:26:22

标签: sql ms-access

我不知道这是否可行 - 并怀疑它可能不是。

我在MS Access 2003中有一个表,列出了数据库中另一个表中存在的一些字段。我想要做的是从另一个表中绘制数据,但是在select语句中使用第一个表中的值定义要绘制的字段。

例如

Table 1
[Sequence]  [Name]
1           CustomerId
2           CustomerName
3           CustomerBirthday

Table 2
[CustomerId]  [CustomerCode]  [CustomerName]  [CustomerType]  [CustomerBirthday]
1             A123            Andrew          A1              Aug
2             A122            Bob             A2              Nov
3             A133            Charles         A1              Jan
4             A153            Diane           A5              Mar

Required Output, using the information defined in table 1:
1  Andrew   Aug
2  Bob    Nov
3  Charles  Jan
4  Diane    Mar

可以按如下方式生成所需的输出:

SELECT CustomerId, CustomerName, CustomerBirthday FROM Table2

但是我希望能够更改字段,因此希望执行以下操作:

SELECT [field name in table1 Where Sequence=1], [field name in table1 Where Sequence=2], [field name in table1 Where Sequence=3] FROM Table2

我知道我可以在代码中执行此操作,但想知道是否有办法在纯SQL中执行此操作,因此我可以将其粘贴到普通查询中。

1 个答案:

答案 0 :(得分:1)

解决方案显然是使用VBA函数“动态”构建SQL查询。根据我的说法,table1应该有一个额外的列,其中包含保存字段的表的名称:

Table 1
[tableName] [Sequence]  [Name]
table2      1           CustomerId
table2      2           CustomerName
table2      3           CustomerBirthday
...
tablen      1           field 1
tablen      2           field 2
...
tablen      i           field i

生成SQL查询的代码将如下所示:

Public function fieldQueryFromTable1(x_tableName as String) as string

Dim rsTable1 as DAO.recordset, _
    m_fieldQuery as String, _
    m_tableQuery as string, _
    a_fieldNames() as string

m_tableQuery = "SELECT name FROM table1 WHERE tableName = """ & x_tablename & """ ORDER BY sequence"

set rsTable1 = currentDb.openRecordset m_tableQuery, dbOpenDynaset, dbReadOnly
a_fieldNames = rsTable1.getrows()   
    'generate a 2 dim array a_fieldName(fieldName, fieldValue)'

set rsTable1 = Nothing

m_fieldQuery = join(a_fieldNames(0),",")   
    'a_fieldNames(0) is a 1 dim array that contains the field names'
    'm_fieldQuery is a string that looks like "field1,field2, ..., fieldi, ..."'


if m_fieldQuery <> "" then
    m_fieldQuery = "SELECT " & m_fieldQuery & " FROM " & x_tableName
    'SELECT field1,field2, ..., fieldi, ... FROM Tablen'
Endif

fieldQueryFromTable1 = m_fieldQuery
end function

这是动态写的,只是为了让你得到这个原则。没有错误处理程序,没有语法检查,没有!我们通常使用ADO记录集做类似的事情,所以我不太确定'getRows'DAO记录集方法bt,根据帮助,它就像ADO记录集一样。