• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 260
  • Last Modified:

Dynamic sql in MS SQL

I have a stored procedure and I need to get a field value from a table based on a dynamic field name and a dynamic key value:

declare @FieldName varchar(255)
set @FieldName = 'myField' <-- in reality this is retrieved from a table

declare @KeyValue varchar(30)
set @KeyValue = 'key' <-- also retrieved from a table in the real world

declare @FieldValue varchar(30) <-- to return the results

select @FieldValue = @FieldName from myTable where keyField = @KeyValue

Then, of course, I have to use @FieldValue later in the stored procedure.

I know that this requires dynamic sql, but after looking at many examples and trying many things, I cannot figure it out.

Thanks in advance for whatever help you can provide
0
g_johnson
Asked:
g_johnson
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
table and column names cannot be given by variables, so you need to really do dynamic sql, like this:
declare @sql nvarchar(max)
set @sql =  'select @FieldValue = [' + @FieldName + '] from myTable where keyField = @KeyValue '
exec sp_executesql @sql, N'@fieldvalue varchar(30) OUTPUT, @Keyvalue varchar(30)', @fieldvalue OUTPUT, @keyvalue 

Open in new window

0
 
g_johnsonAuthor Commented:
Perfect.  Thank you!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now