简体   繁体   English

是否可以使用包含的 SQL 子查询中的值作为其包含查询的表名

[英]Is it possible to use the value from enclosed SQL sub-query to be used as the the table name for its encompassing query

Might be a bit of a strange request, but I'm trying to create a query in SQL that retrieves a value from one of three possible tables whose name, the choice of which is dynamically derived from the value of a field taken from the parent query.可能有点奇怪的请求,但我正在尝试在 SQL 中创建一个查询,该查询从三个可能的表之一中检索一个值,该表的名称是从父字段的值动态派生的询问。

So in theory所以理论上

SELECT doc.[DOC ID], doc.[PO Number], doc.[Supplier Coder], doc.[APPROVER DEPT],
(SELECT [Approver] FROM {dat} WHERE {dat}.[DOC ID] == doc.[DOC ID])
FROM documents doc

where the table name {dat} would be a concatenation of the the string "DEPT" and the value of doc.[APPROVER DEPT].其中表名 {dat} 将是字符串“DEPT”和 doc.[APPROVER DEPT] 值的串联。 For example if the record returned 1 for the APPROVER DEPT field, I would want to retreive the value of the Approver field held in the DEPT1 where the doc IDs match.例如,如果记录为 APPROVER DEPT 字段返回 1,我想检索文档 ID 匹配的 DEPT1 中保存的 Approver 字段的值。

Is this possible to achieve within a single SQL statement?这可以在单个 SQL 语句中实现吗? I can incorporate the query into the existing C# code and provide a solution that way, however, the desired SQL statements are going to be used for views and may be subjected to editing from third parties, so I'd prefer to provide an SQL only solution if possible.我可以将查询合并到现有的 C# 代码中并以这种方式提供解决方案,但是,所需的 SQL 语句将用于视图,并且可能会受到第三方的编辑,因此我更愿意仅提供 SQL如果可能,解决方案。

While you shouldn't have three separate tables storing the same data, I'd recommend using a union if you can't change the schema to be normalized.虽然您不应该让三个单独的表存储相同的数据,但如果您无法将架构更改为规范化,我建议使用联合。

SELECT doc.[DOC ID], doc.[PO Number], doc.[Supplier Coder], doc.[APPROVER DEPT],
(select [Approver] from (
SELECT [Approver], 'DEPT1' as dept, [DOC ID] FROM DEPT1
union all
SELECT [Approver], 'DEPT2' as dept, [DOC ID] FROM DEPT2
union all
SELECT [Approver], 'DEPT3' as dept, [DOC ID] FROM DEPT3
) s where s.[DOC ID] = doc.[DOC ID] and s.dept = doc.[APPROVER DEPT]
)
    FROM documents doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM