Q: Differences in SQL Query I have a question.
This code works:
USE [myDB]
GRANT CONNECT TO [user]

This other code won't (although its execution is done without errors):
DECLARE @nameDB AS VARCHAR (max)= 'myDB'
DECLARE @sql AS VARCHAR(max)
SELECT @sql = 'USE [' + @nameDB + ']'
PRINT @sql
EXEC sp_sqlexec @sql
GRANT CONNECT TO [user]

I need to use the latter (or similar) because I have many databases that need to be in read-only mode for certain user.
Any suggestions?

A: Try this:
DECLARE @nameDB AS sysname = 'myDB'
DECLARE @sql AS VARCHAR(max)
SELECT @sql = 'USE [' + @nameDB + ']; GRANT CONNECT TO [user];'
PRINT @sql
EXEC sp_sqlexec @sql

