列名在单独的表中

时间:2017-06-27 09:17:33

标签: sql sql-server

我需要分析应用程序数据,并将数据存储在定义(列名称)的单独表中。像这样:

mix.styles([
    'resources/assets/css/bootstrap-social.css',
    'resources/assets/css/bootstrap.css',
    'resources/assets/css/dropzone.css',
    'resources/assets/css/jquery-ui.css',
    'resources/assets/css/jquery-ui.structure.css',
    'resources/assets/css/jquery-ui.theme.css',
    'resources/assets/css/nav.css'
],  'public/css/style.css');
mix.scripts([
    'resources/assets/js/pace.js',
    'resources/assets/js/jquery.js',
    'resources/assets/js/page-load.js',
    'resources/assets/js/search.js',
    'resources/assets/js/bootstrap.js',
    'resources/assets/js/dropzone.js',
    'resources/assets/js/homesearch.js',
    'resources/assets/js/image-upload.js',
    'resources/assets/js/jquery-ui.js',
    'resources/assets/js/googlemap.js',
],  'public/js/script.js');

我想得到这样的数据:

Data table1:
id | 1234 | 1235 | 1236
---|------|------|-----
 1 | val1 | val2 | val3

Model:
tableID | colID | Name
--------|-------|-----
 table1 | 1234  | Name
 table1 | 1235  | DOB
 table1 | 1236  | Sex
 table2 | 1237  | Manager
etc...

有可能吗?另外一个问题是,在每个数据表中可能会有不同数量的列。

UPD。
问题由@Prdp解决 虽然,我已经改变了一点点查询:

Data:
id | Name | DOB  | Sex
---|------|------|-----
 1 | val1 | val2 | val3

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,在应用层中更好地处理这个问题。如果你想要一个sql解决方案,那么你需要动态查询

DECLARE @col_list VARCHAR(8000)

SET @col_list = Stuff((SELECT ',' + Quotename(colID) + ' as ' + Quotename(NAME)
                       FROM   Model
                       WHERE  EXISTS (SELECT 1
                                      FROM   information_schema.columns
                                      WHERE  table_name = 'Data'
                                             AND Cast(colID AS VARCHAR(50)) = column_name)
                       FOR xml path ('')), 1, 1, '')

EXEC('select '+@col_list+' from data')