Using a variable to populate select statement

  • HI

    I would like to use a variable to populate my select statement. So I have a 'AREAS' table with a field name AREA and values Area1, Area2, Area3. Now what I want to do is write

    Select Var1

    From Areas

    not

    Select Area

    From Areas

    So I tried something like

    Declare

    @DVar1 Varchar(200)

    set @Var = 'Area'

    begin

    select Var1

    From Areas

    End

    but it returs area not the values I want.

    Please help

  • Is this what you want?

    CREATE TABLE #t(AREA varchar(10))

    INSERT INTO #t VALUES('AREA1')

    INSERT INTO #t VALUES('AREA2')

    INSERT INTO #t VALUES('AREA3')

    DECLARE @VAR1 as varchar(10)

    SELECT TOP 1 @VAR1 = AREA FROM #t

    PRINT @var1

    ---------------------------------------------------------------------------------

  • Yes along those lines but I want to use that variable as a place holder in a select statement where the first step would be to populate the variable then in a select statement.

    e.g where var1 is populated with area1 I would like to use that for my select statement.

    select @var1, value, value

    from table

    would be the equivalent of

    select Area1, value, value

    from table

  • I got the solution guys. A collegue of mine help.

    Declare

    @Var1 Varchar(200)

    set @Var1 = 'Area'

    exec('select Distinct '+@Var1 +'

    From Areas')

    It works wonders

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply