Dynamic sql in MS SQL
Posted on 2014-03-12
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