Select columns from one table based on the column names from another table

前端 未结 3 1589
Happy的楠姐
Happy的楠姐 2020-12-21 05:42

I have 2 tables, one that contains the final results I need, and another that contains the list of columns I need to select from based on a set level.

For example :

相关标签:
3条回答
  • 2020-12-21 05:59

    My previous answer was for mysql. Since the tag has been updated on the question since then, here is the query for sql-server-2008.

    Build a list of columns from the values in table_levels, remove the last ,, build a query string to get you the results from table_results, and then execute.

    DECLARE @listStr varchar(MAX) = ( select selectColumnName + ',' from table_levels where level = 1 for xml path(''))
    DECLARE @query varchar(MAX) = 'SELECT ' + LEFT(@listStr, LEN(@listStr)-1) + ' FROM table_results'
    execute(@query)
    

    Demo for sql server


    Previous answer. Works for mssql

    See demo for mysql

    Use GROUP_CONCAT to make a string out of the values in table_levels and then build a query string to get you the results from table_results

    SET @listStr = ( SELECT GROUP_CONCAT(selectColumnName) FROM table_levels where level = 1);
    SET @query := CONCAT('SELECT ', @listStr, ' FROM table_results');
    PREPARE STMT FROM @query;
    EXECUTE STMT;
    
    0 讨论(0)
  • 2020-12-21 06:01
    declare @cmd varchar(max)
    select @cmd=''
    select @cmd=@cmd+','+[selected-columns]
    from table_levels
    where level=1
    if len(@cmd)>0
    begin
        select @cmd='select '+substring(@cmd,2,len(@cmd))+' from table_result'
        exec(@cmd)
    end
    
    0 讨论(0)
  • 2020-12-21 06:17

    I got it to work by doing what @lobo said with a slight change.

    DECLARE @listStr varchar(MAX);
    set @liststr =
            (
    select [column] + ',' from dbo.columns where nwlevel = '1' for xml path('')
            )
    
    DECLARE @query varchar(MAX);
    set @query =
            (
            'SELECT ' + LEFT(@listStr, LEN(@listStr)-1) + ' FROM staff'
            )
    execute(@query)
    
    0 讨论(0)
提交回复
热议问题