Change database dynamically : Dynamic SQL « Transact SQL « SQL Server / T-SQL Tutorial






4> USE Northwind;
5> DECLARE @db AS NVARCHAR(258);
6> SET @db = QUOTENAME(N'pubs');
7> EXEC(N'USE ' + @db + N'; EXEC(''SELECT DB_NAME();'');');
8> GO








20.18.Dynamic SQL
20.18.1.A stored procedure with dynamic execution.
20.18.2.Simple SELECT query that uses a variable for the field to sequence the result set.
20.18.3.SELECT query with a variable for the table name so that condition determines which table the result set is based on.
20.18.4.Using Stored Procedure to create dynamic sql statement
20.18.5.Change database dynamically
20.18.6.Pass parameters into dynamic sql statement
20.18.7.Build a dynamic sql statement from schema name, table name and column name
20.18.8.create a dynamic sql statement and save it in a varchar type variable