构建动态SQL" FROM"声明

时间:2016-01-08 16:49:36

标签: sql vba ms-access access-vba

我已在 MS ACCESS 2013 中创建了动态SQL字符串构建器,以便为我的用户创建报告。这些报告基本上是从用户可以使用表单控件更改的预设字段池中查询数据。我使用条件语句来构造 SELECT WHERE 语句没问题但是我一直在使用基于表关系的静态字符串生成 FROM 语句。我已经开始收到不明确的外连接错误,但是当我解决它时,我得到重复的报告数据。我想知道是否可以根据用户从不同表中选择的字段动态构建 FROM 语句。

Table relationships I copied the FROM SQL from is shown here

以下是静态 FROM 字符串我正在使用该错误

FROM (((((((tbl_PROJECTS_PARENT LEFT JOIN tbl_PROJECTS_CHILD ON
tbl_PROJECTS_PARENT.WR_ID = tbl_PROJECTS_CHILD.WR_ID) LEFT JOIN 
tbl_PROJECTS_FACILITIES ON tbl_PROJECTS_PARENT.WR_ID = 
tbl_PROJECTS_FACILITIES.WR_ID) LEFT JOIN tbl_SPC_GFEBS_BLDG ON 
tbl_PROJECTS_FACILITIES.FACILITY_ID = tbl_SPC_GFEBS_BLDG.Building) LEFT 
JOIN tbl_CLEARANCE ON tbl_PROJECTS_PARENT.WR_ID = tbl_CLEARANCE.WR_ID) 
LEFT JOIN tbl_RMP ON tbl_PROJECTS_CHILD.ID_WBS = tbl_RMP.ID_WBS) LEFT JOIN 
tbl_RMP_FY ON tbl_PROJECTS_CHILD.ID_WBS = tbl_RMP_FY.ID_WBS) LEFT JOIN 
tbl_COMMENTS ON tbl_PROJECTS_PARENT.WR_ID = tbl_COMMENTS.WR_ID) RIGHT JOIN 
Qry_comments_latest_basic ON tbl_COMMENTS.WR_ID = 
Qry_comments_latest_basic.WR_ID

我为不使用代码插入器而道歉。无法让它显示整个区块。

1 个答案:

答案 0 :(得分:0)

您需要创建包含所有可用字段的查询,并将其作为新表进行查询。

SELECT [user selected field 1], [user selected field 2], [user selected field 3]
FROM (
    SELECT *
    FROM tbl_PROJECTS_PARENT
    LEFT JOIN tbl_PROJECTS_CHILD ON tbl_PROJECTS_PARENT.WR_ID = tbl_PROJECTS_CHILD.WR_ID
    LEFT JOIN tbl_PROJECTS_FACILITIES ON tbl_PROJECTS_PARENT.WR_ID = tbl_PROJECTS_FACILITIES.WR_ID
    LEFT JOIN tbl_SPC_GFEBS_BLDG ON tbl_PROJECTS_FACILITIES.FACILITY_ID = tbl_SPC_GFEBS_BLDG.Building
    LEFT JOIN tbl_CLEARANCE ON tbl_PROJECTS_PARENT.WR_ID = tbl_CLEARANCE.WR_ID
    LEFT JOIN tbl_RMP ON tbl_PROJECTS_CHILD.ID_WBS = tbl_RMP.ID_WBS
    LEFT JOIN tbl_RMP_FY ON tbl_PROJECTS_CHILD.ID_WBS = tbl_RMP_FY.ID_WBS
    LEFT JOIN tbl_COMMENTS ON tbl_PROJECTS_PARENT.WR_ID = tbl_COMMENTS.WR_ID
    RIGHT JOIN Qry_comments_latest_basic ON tbl_COMMENTS.WR_ID = Qry_comments_latest_basic.WR_ID
) AS FullData