Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select with column name like

Tags:

sql

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

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

like image 614
user 4231 Avatar asked Mar 11 '11 15:03

user 4231


People also ask

Can we use like for column name in SQL?

The SQL LIKE OperatorThe LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters.

Can I use like in SELECT SQL?

Description. The SQL LIKE condition allows you to use wildcards to perform pattern matching in a query. The LIKE condition is used in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement.

How do I SELECT only column names in SQL?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'

How do I filter a column name in SQL?

SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE COLUMN_NAME LIKE 'PREFIX%' ORDER BY TABLE_NAME; Query: SELECT * FROM INFORMATION_SCHEMA.


1 Answers

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.

like image 128
Blorgbeard Avatar answered Sep 23 '22 22:09

Blorgbeard