Forum Moderators: open

Message Too Old, No Replies

How to exclude a column/field from select statement (SQL Server)

         

NooK

12:42 pm on Nov 22, 2007 (gmt 0)

10+ Year Member



Basically I am trying to figure out how I can exclude a field from a select statement in Sql Server.

The problem is that php code chooses the table according to some data, thus the table to be queried will differ from time to time so to make 1 consistent query I have to use * (Rather than naming every column which can be different).

The problem is that 1 of the fields appears in all tables with the same name and it is a field I don't want, so I am wondering, how can I exclude that field from the query?

For example


$query = 'SELECT * FROM '.$tableName.' WHERE condition';

$tableName above will be different from query to query

syber

3:05 pm on Nov 22, 2007 (gmt 0)

10+ Year Member



The only way I can think of would be to create a view on each table that includes only the columns that you want to retreive. Your code would now become:

$query = 'SELECT * FROM '.$tableviewName.' WHERE condition';

ZydoSEO

6:51 pm on Nov 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Syber is correct.. Simply create a view which selects all columns except the one you'd like to hide, and select from the view instead of the table.

NooK

3:19 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



I don't see how I can do it because I still have the problem where the table chosen is dynamic meaning I have no way to know which columns will be on that table except that the first column is always the same and it is not wanted and the column from another table (Which is always the same) should be included along with the data.

The only way I see to do that is do a query to retrieve all the dynamic table column names to be included and then another query to create the view (Which would be querying the exact same table again) which sounds a bit too much.

syber

4:16 pm on Nov 27, 2007 (gmt 0)

10+ Year Member



You only have to create the views once.

For example, if you have 50 tables - create 50 views that leave out the first column. Once you have done that, you can change your $query code to reference the view names instead of the table names.