动态SQL“USE [DB]”无效

时间:2016-10-27 11:31:57

标签: sql sql-server sql-server-2012 dynamic-sql

我使用动态sql创建数据库表

这是sql脚本

DECLARE @DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +@DatabaseName+']');
EXECUTE('USE ' + @DatabaseName)
GO
CREATE SCHEMA [Framework]
GO

我得到的错误

Msg 2714, Level 16, State 6, Line 1
There is already an object named 'Framework' in the database.
Msg 2759, Level 16, State 0, Line 1
CREATE SCHEMA failed due to previous errors

此错误,因为EXECUTE('USE'+ @DatabaseName)不起作用

我尝试使用

SET @SQL02  = 'USE ['+ convert(nvarchar(50),@DatabaseName) +']; SELECT DB_NAME();'
exec sp_executesql @SQL02

但没有工作

我能做什么?

3 个答案:

答案 0 :(得分:3)

DECLARE @Query VARCHAR(200); 
SET @Query = CONCAT('USE ', QUOTENAME('<MyDatabase>'), '; ', 'select DB_NAME();');

EXECUTE (@Query);

只要您保持在<MyDatabase>之内,就会返回EXECUTE

答案 1 :(得分:2)

我更喜欢这种形式进行远程执行:

declare @sql nvarchar(max) = N'select Db_Name()';

<DatabaseName>.sys.sp_executesql @sql;

您可以通过制作存储过程将此逻辑放入更方便的形式:

create procedure dbo.usp_ExecuteSqlCommand (
    @databaseName sysname
  , @sqlCommand nvarchar(max)
)
as
begin;
    set nocount on;
    set xact_abort on;

    declare @innerStatement nvarchar(max) = @sqlCommand;
    declare @outerStatement nvarchar(max);

    set @databaseName = QuoteName(ParseName(@databaseName, 1), N'[');
    set @outerStatement = @databaseName + N'.sys.sp_executesql @stmt = @innerStatement;';

    execute sys.sp_executesql
        @stmt = @outerStatement
      , @params = N'@innerStatement nvarchar(max)'
      , @innerStatement = @innerStatement;
end;

用法很明显:

execute dbo.usp_ExecuteSqlCommand
    @databaseName = N'master'
  , @sqlCommand = N'select Db_Name();';

答案 2 :(得分:1)

试试这个:(如果你使用execute,db上下文只会改变那个执行)

DECLARE @DatabaseName VARCHAR(50) = N'test';
EXECUTE ('CREATE DATABASE [' +@DatabaseName+']');
use [test]
go
CREATE SCHEMA [Framework]
GO