Sql-server – SSMS 2012 – loaded saved query not executable (“invalid object name” error)

sql serversql-server-2012ssms

I have multiple saved queries (each one was working fine when I developed them).
But when I load them in SSMS they immediately show error in every table name that's in the script. Moreover, I can't select the relevant DB from "Available databases" box (or any DB on that server, for that matter) and USE [DB_NAME] command does not work, too.

However, if I'll navigate in "Object Explorer" to any table in any DB on the Server I want and do even a simple Select Top 1000, then paste in whole query that's not working – voila – it runs fine.

Is it important for this that I'm connected to multiple SQL servers on different machines at the same time? In case it's needed – all SQL Server 2012.

Does anyone have a thought as to what's happening? It's extremely annoying to go through all the above steps each time I need a query ran. Thanks!

Best Answer

You might need to add "GO" after your "USE [DB_NAME]" statement. Some commands need to be first in the batch. With GO, the USE DB command is executed as first batch, with another batch following it.

So:

USE [DB_NAME]
GO

CREATE PROCEDURE...