Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Changing Database Name Dynamically Using Code\Variables

$
0
0

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.

 


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>