Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using variable as a column heading 1

Status
Not open for further replies.

yehong

Programmer
Sep 22, 2003
291
0
0
US
Hi, I have this dyanamic query in which I want to show the value of a variable @val1 as the column heading.

Declare @val1 varchar(20)
Select @val1='City'
Select id,
case
when table1.field1 = @val1 then table1.field2
end as 'xxxxxxxx' (this should be the value of @val1)
from table1

The result should look like:
ID City
123 Los Angeles

Next time when the value of @val1 is 'Department', then out put should look like
ID Department
123 IT


When I do case...end as @val1, its not working. The val1 can be a city, can be a departement etc.
 
You could use dynamic sql, but it's a much better idea to handle this on the front-end reporting tool or application.
 
Any other opinion please? I need to write this sql in a store proc and I can't use any front-end reporting tool or application.
-thanks.
 
As RiverGuy already said you should uyse so caller Dynamic SQL:
Code:
CREATE PROCEDURE MyTest(
        @ColumnName varchar(500)
        )
AS
BEGIN
    DECLARE @sql varchar(8000)
    SET @sql = 'SELECT Id, '+ @ColumnName+
               '       FROM MyTable'
    EXEC (@sql)
END

Keep in mind that Dynamic Queries are performance killers.

Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
Microsoft MVP VFP
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top