I'm assuming you are using Microsoft SQL Server 7 or later.

declare @fieldname varchar(30)
declare @myquery varchar(500)

select @myquery = 'select ' + @fieldname + ' from authors'

exec (@myquery)


Note however that there are some potential pitfalls with using exec on a
string. The main one is that the query is compiled and executing using the
current users permissions (can cause problems when access to tables is
severely restricted).

David.

----- Original Message -----
From: "Jim Zheng" <[EMAIL PROTECTED]>
To: "Multiple recipients of list delphi" <[EMAIL PROTECTED]>
Sent: Friday, June 22, 2001 3:51 PM
Subject: [DUG]: [DUG-DB]: SQL


> Anyone know how to query a diffrent field value from a table and the field
> name is telled by a char variable?
>
> E.g.
>
> declare @fieldname varchar(30)
> select @fieldname='au_lname'
> select @fieldname from authors
> select @fieldname='au_fname'
> select @fieldname from authors
>
> line 3 and line 5 will return 'au_lname' and 'au_fname'. That isn't what I
> want.
>
> I actually want to display real value of field au_lname and au_fname in
the
> table. Just like select au_lname from authors.
>
> One way I know we can do so,
>
> select
> case
> when @fieldname='au_lname' then au_lname
> when @fieldname='au_fname' then au_fname
> end
> from authors
>
> but is there any other way?
>
> Specially for a table has like 100 fields.
>
>
> Cheers,
>
> Jim
>
> --------------------------------------------------------------------------
-
>     New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
>                   Website: http://www.delphi.org.nz
> To UnSub, send email to: [EMAIL PROTECTED]
> with body of "unsubscribe delphi"

---------------------------------------------------------------------------
    New Zealand Delphi Users group - Delphi List - [EMAIL PROTECTED]
                  Website: http://www.delphi.org.nz
To UnSub, send email to: [EMAIL PROTECTED] 
with body of "unsubscribe delphi"

Reply via email to