Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Select variable column number

Author  Topic 

pop0v
Starting Member

5 Posts

Posted - 2008-12-10 : 06:05:14
Hello.
I want to select different number of columns, depending on some conditions.
Example in pseudocode

SELECT
if @a = 1 then
table.column2 as SomeName
end if
table.column1
table.column3
FROM
table

Any help is greatly appreciated
Sorry for my English.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-12-10 : 06:20:26
[code]SELECT CASE @a
WHEN 1 THEN column2
WHEN 2 THEN columnG
ELSE 'No value selected.'
END AS SomeName,
column1
column3
FROM Table1[/code]


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

pop0v
Starting Member

5 Posts

Posted - 2008-12-10 : 06:26:48
Thanks for the idea, but it doesn't meet my requirements.
If the condition are not met, then no column is selected.
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-12-10 : 06:40:06
Change the ELSE line to meet your (for us unknown) business rules.


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-12-10 : 06:41:17
[code]IF @a = 1
SELECT column2 AS SomeName,
column1
column3
FROM Table1

IF @a = 2
SELECT columnG AS SomeName,
column1
column3
FROM Table1[/code]


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

pop0v
Starting Member

5 Posts

Posted - 2008-12-10 : 06:49:22
We're talking for about 10-11 optional columns in a stored procedure, so i guess this wont work :(
There is a major design flaw in the software i'm co-developing... i'll just think a way to solve the problem.
Thanks again for your responses :) I won't refuse any other :)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-12-10 : 09:37:37
quote:
Originally posted by pop0v

We're talking for about 10-11 optional columns in a stored procedure, so i guess this wont work :(
There is a major design flaw in the software i'm co-developing... i'll just think a way to solve the problem.
Thanks again for your responses :) I won't refuse any other :)


I think you should still be able to use peso's initial solution using case and retyurn unwanted values as NULL. then include code in front end to take only non null values
Go to Top of Page
   

- Advertisement -