typos
typos

Reputation: 6662

How to create a new database and tables inside it in SQL Server?

I'm using T-SQL in order to create a database, and then populate it with tables. The point is that I can create the database successfully, but then when I create the tables it adds them inside the master database, not the newly created one. Here is the code segment that I have:

USE master;  
GO  
CREATE DATABASE Tester  
ON   
(NAME = Tester_dat,  
    FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\tester.mdf',  
    SIZE = 10,  
    MAXSIZE = 50,  
    FILEGROWTH = 5)  
LOG ON  
(NAME = Tester_log,  
    FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\tester.ldf',  
    SIZE = 5MB,  
    MAXSIZE = 25MB,  
    FILEGROWTH = 5MB);  
GO

CREATE TABLE [dbo].[TestCategory](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Category] [nvarchar](20) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
))

I guess the problem might be that I'm using the default schema [dbo], but then again if I replace it with [Tester] I get an error saying that the schema doesn't exist. Any idea, how to switch to the newly created database and create the tables inside it?

Upvotes: 1

Views: 67

Answers (1)

Ilyes
Ilyes

Reputation: 14928

You should add Use.

Use Tester
GO

CREATE TABLE [dbo].[TestCategory](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Category] [nvarchar](20) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Id] ASC
))

GO

Upvotes: 2

Related Questions