SQL Server Performance

passing the column name dynamically

Discussion in 'General Developer Questions' started by pallavi, Nov 8, 2005.

  1. pallavi New Member

    hello

    I want to know can we write a query where we give the column name as variable.

    for eg.
    table1( id , name, value)

    Set @var = 'name'
    Select @var from table1

    or

    Set @var = 'id'
    Select @var form table1

    or is there any other alternative for this.
    if u know comthing abt it pls do let me know

    Thanks in advance

    Pallavi
  2. ranjitjain New Member

    Hi,
    Yes you can pass column name dynamically and to do that you need to use dynamic SQL too.

    for eg.
    table1( id , name, value)

    Set @var = 'name'

    set @cmd='Select '+@var+' from table1'
    exec sp_executesql @cmd
  3. Madhivanan Moderator

  4. pallavi New Member

    Hello

    thanks a lot Ranjit.

    But now i want to use this query for cursor or
    even if i can store the value from this column in a variable it will be ok for me

    Pls can u help me in this


    Pallavi



  5. ranjitjain New Member

    quote:Originally posted by pallavi

    Hello
    thanks a lot Ranjit.
    But now i want to use this query for cursor or
    even if i can store the value from this column in a variable it will be ok for me

    Pls can u help me in this
    Pallavi

    declare @var varchar(50),@cmd nvarchar(500),@var1 varchar(100)

    Set @var = 'aaiuserid'

    set @cmd='Select @var1=count('+@var+') from aaiusers'
    exec sp_executesql @cmd,N'@var1 varchar(100) OUTPUT',@var1 OUTPUT

    select @var1

Share This Page