troubleshooting Question

SQL USE DATABASE VARIABLE

Avatar of Mauro Cazabonnet
Mauro CazabonnetFlag for United States of America asked on
Microsoft SQL Server
5 Comments3 Solutions881 ViewsLast Modified:
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;
SOLUTION
Aneesh
Database Consultant
Join our community to see this answer!
Unlock 3 Answers and 5 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 5 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros