Question Locked

Doing an "indirect" SQL SELECT

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

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.

Thanks!

-tom

5 replies

by tony hopkinson

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.

by dclaassens

Hi Tom,

try this...

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

begin
declare @SQL varchar(250)

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

EXECUTE(@SQL)
end

/**/

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

by behtash

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

by sukh_kaur007

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

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

first select whole procedure and run then for execution part
write

exec st_selectstmt 'sukh'

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

This discussion is closed to new replies.