Avatar of g_johnson
g_johnson
Flag for United States of America

asked on 

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
Microsoft SQL Server 2008

Avatar of undefined
Last Comment
g_johnson

8/22/2022 - Mon