SQL USE DATABASE VARIABLE

Not sure why I'm getting syntax error near GO
on EXEC (@command)

SET NOCOUNT ON;
DECLARE @i int, @dbcount int, @dbname nvarchar(200), @Command nvarchar(4000)

DECLARE @objectid INT;
DECLARE @indexid INT;
DECLARE @partitioncount BIGINT;
DECLARE @schemaname NVARCHAR(130);
DECLARE @objectname NVARCHAR(130);
DECLARE @indexname NVARCHAR(130);
DECLARE @partitionnum BIGINT; 
DECLARE @partitions BIGINT;
DECLARE @frag FLOAT;
DECLARE @dbid SMALLINT;

DECLARE @tempDBnames TABLE
(
	id int,
	dbname nvarchar(200)
)

INSERT INTO @tempDBnames
SELECT ROW_NUMBER() OVER(ORDER BY [name] ASC) AS [id], [name] 
FROM master.dbo.sysdatabases 
WHERE dbid > 4 

SET @dbcount = (SELECT COUNT([dbname]) as [cnt] FROM @tempDBnames)

SET @i = 1
WHILE @i <= @dbcount
BEGIN
	SET @dbname = (SELECT [dbname] FROM @tempDBnames WHERE id = @i)
	
	SET @command = 'USE ' + QUOTENAME(@dbname) + '[CRLF]GO[CRLF]'
	SET @command = REPLACE(@command,'[CRLF]',CHAR(13)+CHAR(10))
	PRINT @command
	EXEC (@command)

	SET @i = @i + 1
END

SET NOCOUNT OFF;

Open in new window

LVL 4
Mauro CazabonnetSenior .NET Software EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aneesh RetnakaranDatabase AdministratorCommented:
'GO' in the dynamic sql is causing the issue

'[CRLF]GO[CRLF]'   -> replace it with a ';'
1
Éric MoreauSenior .Net ConsultantCommented:
what are you trying to do?
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
I agree with Aneesh (you don't need the GO) but like Éric, I'm wondering what are you trying to achieve.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
I was trying to run actions on different databases as I looped thru them
But yes go is not needed

Thx!!!!!
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
Do you know about the undocumented stored procedure sp_MSforeachdb?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.