【问题标题】:Can I select from multiple SQL Server tables without specifying table name我可以在不指定表名的情况下从多个 SQL Server 表中进行选择吗
【发布时间】:2019-08-09 13:29:55
【问题描述】:

我们有一个带有元数据的数据库,可防止表具有重复的列名。有很多表,名字像

product_attributes_1
product_attributes_ext
product_src_1
product_src_2
product_whatever_somenumber

我编写的代码基本上可以提取每个表,并创建一个散列。这行得通,但它真的很慢。

// split the table key to determine the object prefix(s) we need to focus on.
// a table key is XXX_key, if the key differs from that convention, typically
// it means that the current table inherits from a base table.
// For Example: publication (pub_prd_key) inherits from the product table (prd_key).
string[] tableKeys = myObject.GetKeyField().Split('_');

// loop through all of the separated table keys, and load additional properties for the current object  
// based on each table found.
for (int i = 0; i < tableKeys.Length; i++) {
    if (tableKeys[i] != "key"){
        DataClassWrapper data = FacadeClass.GetDataObject(tableKeys[i], databaseObject);
        if (data != null) {
            this.LoadAdditionalProperties(data.TablePrefix, data.TableKey);
        }
    }
}

我想将此代码移动到数据库上的存储过程中,但我不确定如何在 sql 中编写如下内容:

SELECT * 
FROM [mydb].[dbo].[product_*]

我不确定它是否可以完成。我有我的理由,主要是因为我们需要维护提供数据库供我们使用的系统的基本功能。请不要说“列名可能重复”。我知道这一点,我们 100% 确定不会有重复。如果有重复的列名,系统的其余部分将会中断。这就是以这种方式命名表的原因。

另外,我无法重命名这些表。在许可协议中,我们不修改核心功能,无论如何这几乎是不可能的(数据库非常旧且非常大,许多系统都依赖它)。

编辑:我需要指出我的存储过程将采用跨越所有表的ID (guid),因为它们实际上是相互继承的。结果将是 column_name / column_value 的哈希,其中 ID = 一些 guid。它实际上只会从每个表中选择一行。

【问题讨论】:

  • 您可以使用动态 sql 执行此操作,但即使这样也很麻烦。所有这些表都有相同的列吗?如果是这样,您可以使用 UNION 创建包含所有表的查询。但是,如果结构不同,您期望输出什么?
  • 表格都有不同的列。我希望输出是 column->value 的大散列,其中每列都有一个唯一标识符。我已将此添加到我的 q 中。
  • “大哈希”是什么意思?您希望每个表中的列在它们自己的列中吗?这根本没有意义。顺序重要吗?您将不得不对此提供一些说明。
  • 我忘记在其中输入它不是行列表。它将从每个表中返回一行。我的意思是一个大散列是从所有表中取出所有列并将它们连接起来,但不调用每个表名。
  • 为什么不能简单地使用连接?

标签: sql-server concatenation


【解决方案1】:

很确定这可以简化为简单的连接,而不是您所说的这种奇怪的迭代和散列。像这样的东西应该会产生你想要的输出。

select *
from product_attributes_1 pa
join product_attributes_ext pae on pae.MyKey = pa.MyKey
join product_src_1 ps1 on ps1.MyKey = pa.MyKey
join product_src_2 ps2 on ps2.MyKey = pa.MyKey
join product_whatever_somenumber pws on pws.MyKey = pa.MyKey
where pa.MyKey = @MyKey

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多