問題描述
我有一個表 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 查詢,例如作為
- For every obtained
Table_Name
, I need to retrieve correspondingTable_Column
value. Using
Table_Name
andTable_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模板網!