0

Assuming I have a list of values after a select from a table:

DEPARTMENT(Table):

+-----------+---------+-----------+-----------+
| DEPT_NAME | DEPT_ID | DEPT_CITY | DEPT_TYPE |
+-----------+---------+-----------+-----------+
|           |         |           |           |
+-----------+---------+-----------+-----------+

Now, my SELECT Query should be:

SELECT DEPT_NAME,DEPT_ID,DEPT_CITY from LOCATIONS table where (external condition);
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
  • so you want to take the values from one table and use them as the fields in the select part of a sql statement? – Thomas Nov 26 '15 at 07:00

2 Answers2

0

i think this can be done using pivot table.

please check this this tutorial http://www.artfulsoftware.com/infotree/queries.php#78

further you can check these in SO itself, MySQL pivot table

Community
  • 1
  • 1
Akhil S Kamath
  • 1,012
  • 13
  • 23
0

if you're using MS SQL you can use the FOR XML Path('') statement and create dymanic sql query as followed:(I dnn't have access to other SQL Management Systems so I don't know if this would work for them.

DECLARE @columns varchar(255) = (select ',' + [Column] FROM (Values('DEPT_NAME'),('DEPT_ID'),('DEPT_CITY'),('DEPT_TYPE')) as tColumns([column])FOR XML PATH(''))
--select @columns

DECLARE @stmt varchar(255) = 'Select 1 as DummyColumn ' + @columns + ' from LOCATIONS table where (external condition);'
--select @stmt
EXEC(@stmt)

in this case I'm using 255 as the length of the variables; but you can change that to anything of your liking.

(Values('DEPT_NAME'),('DEPT_ID'),('DEPT_CITY'),('DEPT_TYPE')) as tColumns([column]) is an inline values table; you need to replace this with the correct select statement.

NPToita
  • 238
  • 2
  • 9