Creating and Executing a Variable as a Query

Question:
How do I create a stored procedure that will construct and execute a query from its parameters?

At the heart I’d imagine something like this, for simplicity’s sake:

declare @foobar varchar(255)select @foobar = "select * from aTable"exec @foobar

I know removing the ‘exec’ command doesn’t launch the query.

Answer:
You actually are on track. You need to make only one slight change—place parentheses around @foobar, like this: exec(@foobar).

So to make your example complete, try the following:

use pubsgocreate procedure sp_foobar(	@foobar varchar(100))asexec (@foobar)gosp_foobar 'select * from authors'

This technique has some gotcha’s though. First of all, you can’t create a dynamic SQL statement that sets a variable in the stored procedure. So the following statement won’t work:

declare @foobarexec('select @foobar = ...')

You can also run into problems if you are trying to build a command string from fields or sources that have either single quotes or double quotes in them.

However, dynamic SQL can be very useful in some situations. On a recent project, I needed to save the changes made in one database and apply them to another. I’m going to skip the details of why I couldn’t simply use replication. I created an audit trail that had the name of the table, primary key value, field name, and old and new values. Using dynamic SQL, I was then able to reconstruct the necessary update statement and apply it to the second database.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a