Skip to content

SQL Server tips: Executing a query with the EXECUTE command

This short SQL Server blog post is meant to help people who have experienced the error messages 2812 and 203 with the EXECUTE command.
The goal is to execute a simple query from a variable in a string format with the EXECUTE (exec) command.
Very easy, isn’t it?
Ok, let’s GO!

If I execute “select * from sys.databases” in SSMS, in SQLCMD or in PowerShell – no problem, I have the list of all databases from my instance:

Execute01.png

The next step is to create a variable with this command and to execute this simple command:

Execute02.png

The error message is:

Msg 2812, Level 16, State 62, Line 3
Could not find stored procedure ‘select * from sys.databases’.

It cannot find the stored procedure.

I have indicated the full name of the object (database.schema.object) in the query with the database master and [] around the objects to be sure.

Remarks: I have tested without the database master and it the result was good. The real difference is to use brackets.

Execute03.png

Now, the error message is:

Msg 203, Level 16, State 2, Line 3
The name ‘select * from [master].[sys].[databases]’ is not a valid identifier.

The problem comes from the EXECUTE command. If you don’t use “()” for your variable, the variable is considered like a stored procedure and not like a query.

When you use “()”, the query is really interpreted like a query.

Execute04.png

Finally, it is good to know how the EXECUTE command works and why we have error messages. I hope this can help developers and perhaps some DBAs…

Let’s work together

Ready to operate at
the next level?

Tell us about your challenge. We’ll bring the depth, the expertise, and the Swiss precision.

Stéphane Haby

Stéphane Haby

Stéphane Haby has more than 20 years of experience in Microsoft solutions, specializing in the installation, migration, best practices, and performance analysis of Microsoft SQL Server, as well as Microsoft Business Intelligence solutions (SharePoint, Office) and .NET development for the banking sector. A former Microsoft Most Valuable Professional (MVP) and early adopter of Microsoft Team System in France, he has authored several technical articles. He holds Microsoft Certified Solutions Associate (MCSA) and Expert (MCSE) for SQL Server, MCTS, MCITP for SQL Server 2008, and ITIL V3 Foundation certifications. His industry experience covers chemicals and pharma, banking, and financial services.View Author posts

182 posts since April 2011

Leave a Comment

Your email address will not be published. Required fields are marked *