简体   繁体   中英

SQL - Select Columns from table where another table column value equals column name list

seen a lot of similar posts about parsing data based on values but nothing quite what I want to get the result column from one table that contains the column names for another table. For example:

 Select [col1], [col2]
 from Table1
 where (select changes as (col#)
        from table2)

The col# is a list of the column names I want from Table1. Table2 changes column is a comma separated list. I wanted to figure a way to be able to get each column from Table1 that's in the list from table2. Any help is greatly appreciated.

You'll have to create the query on-the-fly. You can either do this by:

  1. First fetching the data from the changes column into your calling application, then assembling a SQL query string from that data and execute it, or
  2. Creating a dynamic statement within a stored procedure and EXEC ing it (or whatever your RDBMS's equivalent statement is).

Do be aware though that if the data in changes ever comes from user input, you are in for a world of hurt.

If you have control over the schema I would suggest to avoid this way of storing data. In general, comma-separated-lists are just unwieldy and fundamentally go against what a database is designed to do. A change-table structure with one Boolean value for each column that could change (id, col1_changed, col2_changed) or with a single row for each changed column (id, changed_col_name) would be much easier to use in a normal query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM