I have a script that can be represented by the following:
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
The problem is when I create the table after it's not created in the new database but in whatever database I am currently on.
Any idea on how to use a database that you just created and don't know the name in advance?
2条答案
按热度按时间0vvn1miw1#
c3frrgcw2#
One possible solution to your problem is handling this server side.
Use the following as a guiding example: