February 6, 2013 by Kenneth Fisher
The other day one of the developers I work with gave me a script similar to this:
BEGIN TRAN sp_rename 'tablename.columnname', 'newcolumnname' COMMIT
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.
BEGIN TRAN EXEC sp_rename 'tablename.columnname', 'newcolumnname' COMMIT
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.