I'm brand-new to mySQL and sql in general. I have install mysql workbench and mysql community server to start practicing as I saw in many tutorials. I have 2 problems possibly connected to each other. In many scripts I see the usage of
USE master;
in my version of workbench ( version 8.0) when I try to run this query is says "unknown database 'master'. I'm not pretty sure what master database has ( I googled it and I only understood that is a good practice to make your own database inside master database).
My other question which is more confusing for me is when I use IF.
IF NOT EXISTS(SELECT name FROM master.dbo.sysdatabases
WHERE name = 'mydatabase')
CREATE DATABASE [mydatabase]
It keeps giving me the error: "IF is not valid at this position, expecting EOF,ALTER,ANALYZE,BEGIN , ..."
When I use BEGIN before the IF is says :IF is not valid at this position, expecting EOF, ';'
At first I assumed it has something to do with the master database so I tried something different:
IF OBJECT_ID('tablename','U') IS NULL
CREATE TABLE tablename(
....);
I get the same errors. The only thing I found on stackoverflow is this: statement-is-not-valid-in-this-position Where someone says " You cannot use IF in an SQL statement. You can only use it in a stored procedure or a function " if that's the case how does the scripts I find online use the IF statement this way? This is an example of an sql code that is supposed to work:
USE [master]
GO
IF NOT EXISTS (SELECT name FROM master.dbo.sysdatabases
WHERE name = 'HotelManagement')
CREATE DATABASE [HotelManagement] COLLATE Greek_CI_AI -- Collatiom : CI = Case Insensitive, AI = Accent Insensitive
GO
/* =====================
CREATE ENTITIES
======================*/
USE [HotelManagement]
GO
IF OBJECT_ID ('Customers', 'U') IS NULL
BEGIN
CREATE TABLE Customers
(
Customer_ID int IDENTITY(1,1) PRIMARY KEY,
First_name varchar (50) not null,
Last_name varchar (50) not null,
Birth_date datetime,
Issuing_authority varchar (50) not null,
Email varchar (50),
Phone varchar (50)
)
END