You need to declare your variable within the scope of the execute statement:declare @command1 nvarchar(2000);set @command1 = N'DECLARE @COPYDatabaseUserName [sysname]; SET @COPYDatabaseUserName = ''Domain\Laurine Torrone''; SELECT @CopyDatabaseUserName';EXEC sp_MsForEachDb @command1;
or, construct the statement prior to executing. Sounds like you might want this option if the variable is needed further in the script:DECLARE @COPYDatabaseUserName [sysname]SET @COPYDatabaseUserName = 'Domain\Laurine Torrone';declare @cmd nvarchar(2000);set @cmd = 'SELECT S.[name],S.[principal_id],R.[role_principal_id],''ROLE'' AS [role_name],S.[default_database_name],S.[default_language_name]FROM ?.sys.server_principals SINNER JOIN ?.sys.server_role_members RON R.[member_principal_id] =s.[principal_id]WHERE S.[name] = ' + quotename(@COPYDatabaseUserName, '''');print @cmdEXEC sp_MsForEachDb @cmd;