Is there a way to persist a variable across a go?
Declare @bob as varchar(50);
Set @bob = 'SweetDB';
GO
USE @bob --- see note below
GO
INSERT INTO @bob.[dbo].[ProjectVersion] ([DB_Name], [Script]) VALUES (@bob,'1.2')
See this SO question for the 'USE @bob' line.
Temp tables are retained over GO statements, so...
It's not pretty, but it works
Use a temporary table:
The
go
command is used to split code into separate batches. If that is exactly what you want to do, then you should use it, but it means that the batches are actually separate, and you can't share variables between them.In your case the solution is simple; you can just remove the
go
statements, they are not needed in that code.Side note: You can't use a variable in a
use
statement, it has to be the name of a database.Not sure, if this helps
I prefer the this answer from this question Global Variables with GO
Which has the added benefit of being able to do what you originally wanted to do as well.
The caveat is that you need to turn on SQLCMD mode (under Query->SQLCMD) or turn it on by default for all query windows (Tools->Options then Query Results->By Default, open new queries in SQLCMD mode)
Then you can use the following type of code (completely ripped off from that same answer by Oscar E. Fraxedas Tormo)
you could use dynamic sql, just be aware of security risks with this (not 100% sure on the correct syntex)
declare @bob nvarchar(50)