Web Development



Doing an "indirect" SQL SELECT

By ttobin100 ·
Does anyone know how I can do an "indirect" SQL SELECT statement? (one in which the column to return from a table is not named explicitly, but is contained in a variable?)

For example, instead of this:

SELECT trailer FROM .... WHERE ...

I need to be able to do something like this:

DECLARE @FieldName nVarChar(30)
SELECT @FieldName = 'trailer'
SELECT @FieldName FROM ... WHERE ...

The third line in my example above doesn't work like I need it to.



This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Answers

Collapse -

With Exec like this

by Tony Hopkinson In reply to Doing an "indirect" SQL S ...

DECLARE @FieldName nVarChar(30)
Declare @sqlstring nVarChar(255)
SELECT @FieldName = 'trailer'
Select @sqlstring = 'Select ' + @FieldName + ' From ... Where ...'
Exec (@sqlstring)

The parenthesis are mandatory and be real careful if you build the string from user input.

Collapse -


by dclaassens In reply to Doing an "indirect" SQL S ...

Hi Tom,

try this...

create procedure GetFields
@sFieldname varchar(50),
@sTablename varchar(50)

declare @SQL varchar(250)

SET @SQL = 'Select ' + @sFieldname + ' from ' + @sTablename



DECLARE @sFieldname varchar(50)
DECLARE @sTablename varchar(50)

SET @sFieldname = 'Happy_field_name'
SET @sTablename = 'Happy_table_name'

exec GetFields @sFieldname, @sTablename

Kind Regards

Deon Claassens

Collapse -


by behtash In reply to Doing an "indirect" SQL S ...

execute sp_executesql N'select '+@feildname+' from '+@tablename+''

Collapse -

Indirect SQL select

by sukh_kaur007 In reply to Doing an "indirect" SQL S ...

Hi Tom,
I have created procedure for indirect select statement.first create procedure then execute it

create proc st_selectstmt
@name varchar(20)
set @name ='sukh'
select name=@name,SALARY from employees where salary=2250

first select whole procedure and run then for execution part

exec st_selectstmt 'sukh'

select and run again
you will get all name having 'sukh' whose salary =2500.

Related Discussions

Related Forums