EXECUTE, not required, but advisable.


February 6, 2013 by Kenneth Fisher

The other day one of the developers I work with gave me a script similar to this:

sp_rename 'tablename.columnname', 'newcolumnname'

He was getting the error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'tablename.columnname'.

Now most of you probably realize that had he just ran the sp_rename it would have worked just fine.

So why was the error generated? Was it because sp_rename can’t be put in a transaction? Nope, it works just fine in the transaction with a minor change to the code.

What you have to remember is that if a stored procedure is the first thing in a batch then it is executed without the need for the explicit EXECUTE command. In this case the stored procedure name was not the first thing in the batch. The BEGIN TRANSACTION statement was. All of that means that with a simple change to the code it works correctly.

EXEC sp_rename 'tablename.columnname', 'newcolumnname'

I had a fellow DBA tell me one time “If you always do it right, you will always do it right.” It sounds a little bit odd at first and at the time he was talking about using batch processing vs using loops and cursors. Very basically what he meant was that if you keep up good coding habits you will run into fewer issues. In this particular case getting into the habit of putting EXEC or EXECUTE in front of your stored procedure calls. This way the stored procedure calls will work regardless of their placement in the batch.

One thought on “EXECUTE, not required, but advisable.

  1. […] wrote about this one time here. This one is a good habit anyway, but particularly with dynamic SQL. SQL Server only runs a stored […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,753 other subscribers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: