Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

I want to select columns based on condition
I have a table like

Table:

ID~Phone1~Phone2~Phone3~Phone4~Phone5
1~99~88~0~0~77


Now I want to select only the column and its value that is greater than 0 that is

Expected result:

ID~Phone1~Phone2~Phone5
1~99~88~77

If all phonenumber is < 0 then should return ID alone.

Regards,
RK
Posted
Updated 4-Feb-14 18:44pm
v2

1 solution

Hi Friends,

Here is what I have tried,
SQL
DECLARE @query VARCHAR(1000)=null;
SET @query = 'ID';
IF((select phone1 from tablename where id = 1459) > 0)
    SET @query += ',phone1';
    IF((select phone2 from tablename where id = 1459) > 0)
    SET @query += ',phone2';
    ..
    ..
    ..
IF (@query IS NOT NULL)
exec('SELECT '+@query+' FROM tablename WHERE id = 1459');

I do not know whether the above solution is optimal or not but it gives me expected answer.So I selected the above method.

Hope this may help someone too.

Regards,
RK
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900