Question

Locked

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.

Thanks!

-tom

This conversation is currently closed to new comments.

4 total posts (Page 1 of 1)  
| 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 -

Exec

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

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

Collapse -

sp_execute

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)
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.

Back to Web Development Forum
4 total posts (Page 1 of 1)  

Related Discussions

Related Forums