Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there any way to set a variable off of dynamic sql? 1

Status
Not open for further replies.

VVVA

Technical User
Sep 19, 2006
35
US
Is there any way I can do something like this without dropping out to a UDF?

Code:
declare @CMD varchar(4000)
declare @Field1 varchar (20)
declare @Result varchar (40)

set @Field1 = 'Name'

set @CMD = 'select top 1 '+@Field1+' from MyTable'
print @CMD
set @Result = (exec (@CMD))
 
That is very easy with sp_executesql

Code:
DECLARE @Field1 VARCHAR(100),
@Result varchar(20),
@chvSQL NVARCHAR(100)

set @Field1 = 'au_lname'
SELECT @chvSQL = N'SELECT top 1 @Result =' + @Field1 + ' from Authors'

EXEC sp_executesql @chvSQL, N'@Result varchar(20) OUTPUT', @Result OUTPUT

SELECT @Result
GO

so in your case

Code:
DECLARE @Field1 VARCHAR(100),
@Result varchar(20),
@chvSQL NVARCHAR(100)

set @Field1 = 'Name'
SELECT @chvSQL = N'SELECT top 1 @Result =' + @Field1 + ' from MyTable'

EXEC sp_executesql @chvSQL, N'@Result varchar(20) OUTPUT', @Result OUTPUT

SELECT @Result
GO

Denis The SQL Menace
SQL blog:
 
btw the first example use the pubs database
here it is again for anyone who wants to try it

Code:
USE PUBS
GO


DECLARE @Field1 VARCHAR(100),
@Result varchar(20),
@chvSQL NVARCHAR(100)

set @Field1 = 'au_lname'
SELECT @chvSQL = N'SELECT top 1 @Result =' + @Field1 + ' from Authors'

EXEC sp_executesql @chvSQL, N'@Result varchar(20) OUTPUT', @Result OUTPUT

SELECT @Result
GO

Denis The SQL Menace
SQL blog:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top