I have SQL where I am trying to change to a different database dynamically inside a cursor or while loop:
DECLARE @SQL nvarchar(2000) DECLARE @DBName sysname SET @DBName= 'Datasets' SET @SQL = 'USE ' + QUOTENAME(@dbname) select @SQL execute @SQL
It does not work and gives this error:
Msg 203, Level 16, State 2, Line 9 The name 'USE [Datasets]' is not a valid identifier.
I have tried using different data types, putting a 'go' at the end of the @SQL variable, etc..
Has anybody made something like this work? Thanks in advance.