sql use statement with variable

The problem with the former is that what you’re doing is USE 'myDB' rather than USE myDB.
you’re passing a string; but USE is looking for an explicit reference.

The latter example works for me.

DECLARE @sql varchar(20)
SELECT @sql="USE myDb"
EXEC sp_sqlexec @Sql

-- Also works
SELECT @sql="USE [myDb]"
EXEC sp_sqlexec @Sql

Leave a Comment

tech