Answers:
您可以使用嵌套EXEC
调用。由USE
持久性更改的数据库上下文将保留到子批处理。
DECLARE @DB SYSNAME
SET @DB = 'tempdb'
DECLARE @CreateViewStatement NVARCHAR(MAX)
SET @CreateViewStatement = '
USE '+ QUOTENAME(@DB) +';
EXEC(''
CREATE VIEW [dbo].[MyTable] AS
SELECT 1 AS [Foo]
'')
'
EXEC (@CreateViewStatement)