Solved

Dynamic sql in MS SQL

Posted on 2014-03-12
2
251 Views
Last Modified: 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
0
Comment
Question by:g_johnson
2 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 500 total points
ID: 39923922
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
 
LVL 4

Author Closing Comment

by:g_johnson
ID: 39924087
Perfect.  Thank you!
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

832 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question