从存储在表中的表/列名称构建查询

Build queries from table/column names stored in a table(从存储在表中的表/列名称构建查询)
本文介绍了从存储在表中的表/列名称构建查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个表 TABLES_IDS 看起来像这样:

I have a table TABLES_IDS that looks like this:

Table_ID  Table_Name  Table_Column
--------  ----------  ------------
100       Attributes  Attribute_id
101       NewSamples  Section_id
...

我有一个第一次查询",它返回多个 Table_Name 的值.这个Table_Name其实是另一个表的名字,而Table_Column是一列.我需要执行以下操作:

I have a "first query" that returns several values of Table_Name. This Table_Name is actually the name of another table, and Table_Column is a column. I need to do the following:

  1. 对于每个获得的Table_Name,我需要检索相应的Table_Column 值.
  2. 使用 Table_NameTable_Column,创建一个新的 sql 查询,例如作为

  1. For every obtained Table_Name, I need to retrieve corresponding Table_Column value.
  2. Using Table_Name and Table_Column, create a new sql query that looks e.g. as

SELECT FROM Table_Name WHERE Table_Column = 12345

  • 为第一个查询返回的每个 Table_Name 自动重复所有操作.

    推荐答案

    如果我理解您的问题,您想根据存储在此表中的表/列名称运行一系列查询.您不能将表名和列名作为变量或来自查询或表达式的结果来引用,因此您需要使用动态 SQL,例如

    If I understand your question, you want to run a series of queries based on the table / column name stored in this table. You can't reference table and column names as variables or coming from the result of a query or expression, so you need to use dynamic SQL, e.g.

    DECLARE @sql NVARCHAR(MAX);
    
    SET @sql = N'';
    
    SELECT @sql = @sql + N'SELECT * FROM dbo.' 
      + QUOTENAME(Table_Name) + ' WHERE ' 
      + QUOTENAME(Table_Column) + ' = 12345;'
    FROM dbo.TABLES_IDS
    -- WHERE...
    ;
    
    EXEC sp_executesql @sql;
    

    这篇关于从存储在表中的表/列名称构建查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!
  • 相关文档推荐

    ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
    SQL query to group by day(按天分组的 SQL 查询)
    What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
    MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
    MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
    Include missing months in Group By query(在 Group By 查询中包含缺失的月份)