sql select with column name like

前端 未结 8 1221
盖世英雄少女心
盖世英雄少女心 2020-12-02 15:46

I have a table with column names a1,a2...,b1.b2....

How can I select all those with column names like a%?

8条回答
  •  囚心锁ツ
    2020-12-02 15:59

    This will get you the list

    select * from information_schema.columns 
    where table_name='table1' and column_name like 'a%'
    

    If you want to use that to construct a query, you could do something like this:

    declare @sql nvarchar(max)
    set @sql = 'select '
    select @sql = @sql + '[' + column_name +'],'
    from information_schema.columns 
    where table_name='table1' and column_name like 'a%'
    set @sql = left(@sql,len(@sql)-1) -- remove trailing comma
    set @sql = @sql + ' from table1'
    exec sp_executesql @sql
    

    Note that the above is written for SQL Server.

提交回复
热议问题