Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

sql - Is it possible to use a returned column value as a table name in an SQLite query?

I want to write a query that examines all the tables in an SQLite database for a piece of information in order to simplify my post-incident diagnostics (performance doesn't matter).

I was hoping to write a query that uses the sqlite_master table to get a list of tables and then query them, all in one query:

SELECT Name 
FROM sqlite_master
WHERE Type = 'table' AND (
    SELECT count(*)
    FROM Name
    WHERE conditions
    ) > 0;

However when attempting to execute this style of query, I receive an error no such table: Name. Is there an alternate syntax that allows this, or is it simply not supported?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SQLite is designed as an embedded database, i.e., to be used together with a 'real' programming language. To be able to use such dynamic constructs, you must go outside of SQLite itself:

cursor.execute("SELECT name FROM sqlite_master")
rows = cursor.fetchall()
for row in rows:
    sql = "SELECT ... FROM {} WHERE ...".format(row[0])
    cursor.execute(sql)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...