【问题标题】:Drawing dynamically defined fields in MS Access在 MS Access 中绘制动态定义的字段
【发布时间】:2010-02-04 11:26:22
【问题描述】:

我不知道这是否可能 - 并且怀疑可能不会。

我在 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 中做到这一点,以便我可以将其粘贴到普通查询中。

【问题讨论】:

  • 我不明白你的意思?
  • 我认为你将不得不使用代码。

标签: sql ms-access


【解决方案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 一样工作。

【讨论】:

  • 谢谢,我最终找到了另一种方法,但接受了您的回答,因为它符合我的要求。
  • 你的替代方法是什么?我对你的发现很感兴趣。提前致谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
相关资源
最近更新 更多