Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL script not creating the tables

I am currently trying to make a simple database but everytime I run the script, it creates the database, but does not create any of the tables, any ideas?

use master
IF EXISTS(select * from sys.databases where name = 'MyWebDB')
DROP DATABASE MyWebDB

CREATE DATABASE MyWebDB
DROP TABLE Users
CREATE TABLE Users
(
UserID int IDENTITY PRIMARY KEY,
EmailAddress varchar(100) NOT NULL,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
);
CREATE TABLE Products(
ProductID int IDENTITY PRIMARY KEY,
ProductName varchar(100) NOT NULL
);
DROP TABLE Downloads
CREATE TABLE Downloads(
DownloadID int IDENTITY PRIMARY KEY,
UserID int FOREIGN KEY REFERENCES Users(UserID),
DownloadDate datetime NOT NULL,
FileName varchar(100) NOT NULL,
ProductID int FOREIGN KEY REFERENCES Products(ProductID)
);
like image 847
OysterMaker Avatar asked Apr 27 '26 07:04

OysterMaker


1 Answers

Get rid of your drop tables and make sure to change your database context by using the USE keyword and the database name. If you want to check for the existence of the table like you are doing with the database, query if exists from sys.tables.

USE master
GO
IF EXISTS(select * from sys.databases where name = 'MyWebDB')
DROP DATABASE MyWebDB

CREATE DATABASE MyWebDB
USE MyWebDB
GO
CREATE TABLE Users
(
UserID int IDENTITY PRIMARY KEY,
EmailAddress varchar(100) NOT NULL,
FirstName varchar(50) NOT NULL,
LastName varchar(50) NOT NULL,
);
CREATE TABLE Products(
ProductID int IDENTITY PRIMARY KEY,
ProductName varchar(100) NOT NULL
);
CREATE TABLE Downloads(
DownloadID int IDENTITY PRIMARY KEY,
UserID int FOREIGN KEY REFERENCES Users(UserID),
DownloadDate datetime NOT NULL,
FileName varchar(100) NOT NULL,
ProductID int FOREIGN KEY REFERENCES Products(ProductID)
);
like image 136
John Specko Avatar answered Apr 29 '26 01:04

John Specko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!