我有一个表 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:
Table_Name,我需要检索相应的Table_Column 值.使用 Table_Name 和 Table_Column,创建一个新的 sql 查询,例如作为
Table_Name, I need to retrieve corresponding Table_Column value.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;
这篇关于从存储在表中的表/列名称构建查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
将每个子标记转换为具有多个分隔符的单列-SQLConverting Every Child Tags in to a Single Column with multiple Delimiters -SQL Server (3)(将每个子标记转换为具有多个分隔符的单列-SQ
如何从多个表创建视图?How can I create a view from more than one table?(如何从多个表创建视图?)
根据前一行内的计算值创建计算值Create calculated value based on calculated value inside previous row(根据前一行内的计算值创建计算值)
如何将表格的前两列堆叠成一列,但也仅将第三How do I stack the first two columns of a table into a single column, but also pair third column with the first column only?(如何将表格的前两列堆
递归 t-sql 查询Recursive t-sql query(递归 t-sql 查询)
将月份名称转换为日期/月份编号(问题和答案的组Convert Month Name to Date / Month Number (Combinations of Questions amp; Answers)(将月份名称转换为日期/月份编号(问题和答案的组合