SQL Server动态创建数据库并在脚本中使用数据库

时间:2018-01-07 16:33:43

标签: sql-server

我有一个可以用以下代码表示的脚本:

DECLARE @DatabaseNamePart VARCHAR(50) = 'Part1'
DECLARE @DataBaseName VARCHAR(70) = 'MyDataBase_' + @DatabaseNamePart

IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE [name] = @DataBaseName) BEGIN
    DECLARE @SqlQuery NVARCHAR(150) = 'CREATE DATABASE ' + @DataBaseName
    EXECUTE (@SqlQuery)     
END

DECLARE @UseDatabase NVARCHAR(150) = 'USE ' + @DataBaseName
EXECUTE ( @UseDatabase )

/**************************************************************************/
/*                           CREATE TABLES                                */
/**************************************************************************/

IF NOT EXISTS (SELECT * FROM sysobjects WHERE [name]='MyTable' AND xtype='U') BEGIN
    CREATE TABLE MyTable (
        [id] INT PRIMARY KEY NOT NULL IDENTITY,
        [Name] VARCHAR(150) NOT NULL,
    )
END

问题是当我在新数据库中创建表但未在我当前使用的任何数据库中创建表时。

有关如何使用您刚创建的数据库并且事先不知道该名称的任何想法吗?

1 个答案:

答案 0 :(得分:0)

DECLARE @DatabaseNamePart VARCHAR(50) = 'Part1'
DECLARE @DataBaseName VARCHAR(70) = 'MyDataBase_' + @DatabaseNamePart

IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE [name] = @DataBaseName) BEGIN
    DECLARE @SqlQuery NVARCHAR(150) = 'CREATE DATABASE ' + @DataBaseName
    EXECUTE (@SqlQuery)     
END



-- code edited - declaring a new variable and setting the dbname

Declare @newDBName VARCHAR(30)

SET @DBName = @DataBaseName

exec('USE '+ @DBName)

-- code edited


--Create tables query

IF NOT EXISTS (SELECT * FROM sysobjects WHERE [name]='MyTable' AND xtype='U') BEGIN
    CREATE TABLE MyTable (
        [id] INT PRIMARY KEY NOT NULL IDENTITY,
        [Name] VARCHAR(150) NOT NULL,
    )
END