"There is already an object named XXXX in the database" after creating New database - sql

I have an SQL file which I am executing on an SQL Server instance which contains the schema for a database. The file creates a brand new database (as in, a database with this name does not exist on this server):
CREATE DATABASE PROJECT;
and begins to create a relation:
CREATE TABLE Courses (
CourseID INT NOT NULL PRIMARY KEY,
Name VARCHAR(64) NOT NULL UNIQUE,
Code CHAR(4) NOT NULL UNIQUE
);
...
and here is what SQL Server tells me right off the bat:
Msg 2714, Level 16, State 6, Line 3
There is already an object named 'Courses' in the database.
Any idea why SQL Server tells me that there already exists a relation by the name of Courses when clearly there isn't?
Thank you for your time.

Check the database if you are using PROJECT
CREATE DATABASE PROJECT
GO
USE PROJECT
GO
CREATE TABLE Courses
(
CourseID INT NOT NULL PRIMARY KEY,
Name VARCHAR(64) NOT NULL UNIQUE,
Code CHAR(4) NOT NULL UNIQUE
)
GO

You are likely missing USE PROJECT statement and therefore trying to create Courses table in the master database, not in the PROJECT database.

Long shot but try using:
Use project;
CREATE TABLE Courses....

Related

Why schema is required while creating a table and not while querying a table - SQL server

I'm new to the MS SQL server. Our client has given us a SQL server DB and for this DB they have configured the Service Principal Authentication. So I logged into the DB using my client company account and then I tried to create a table without giving any schema name. for example
CREATE TABLE visits (
visit_id INT PRIMARY KEY IDENTITY (1, 1),
first_name VARCHAR (50) NOT NULL,
last_name VARCHAR (50) NOT NULL,
visited_at DATETIME,
phone VARCHAR(20),
store_id INT NOT NULL,
);
so when I ran this query it gave me the below error
Msg 2760, Level 16, State 1, Line 1
The specified schema name "aashay.amballi#<company>.com" either does not exist or you do not have permission to use it.
so now when I created the table with DBO schema it created the table.
CREATE TABLE dbo.visits (
visit_id INT PRIMARY KEY IDENTITY (1, 1),
first_name VARCHAR (50) NOT NULL,
last_name VARCHAR (50) NOT NULL,
visited_at DATETIME,
phone VARCHAR(20),
store_id INT NOT NULL,
);
So now when I tried to query this visits table without any schema (i.e. DBO) select * from visits it actually gave me the result.
Also when I ran the select SCHEMA_NAME() to check what is the default schema, it returned null. So is there a possibility that when there is no default schema that is set for a user and while creating a table without a schema name it will give that error? if that is the case then while querying without any schema how it's picking the dbo schema by default?
So I'm a bit confused about how this is working. Can anyone please explain this?
This question is regarding the question that I asked a couple of days back when I'm trying to integrate MSSQL with service principal authentication with the Django Framework - Django MigrationSchemaMissing exception on Azure SQL using service principal auth
From the CREATE TABLE description:
If type_schema_name isn't specified, the SQL Server Database Engine
references type_name in the following order:
The SQL Server system data type.
The default schema of the current user in the current database.
The dbo schema in the current database.
And what is your default schema? It depends on options of CREATE USER statement used when creating your user's account:
WITH DEFAULT_SCHEMA = schema_name Specifies the first schema that will
be searched by the server when it resolves the names of objects for
this database user.
You can skip the schema in queries, but it is a best practise to always use schemas.

How do I create a postrgresql database using SQL's DDL on pgadmin4?

I'm learning DDL to create and define an SQL database with Postgresql 10.
I have the something like the following SQL code in an .sql file, and I want to input it in psql or PgAdmin 4, just to test the syntax and see the database structure:
CREATE DATABASE database;
CREATE TYPE t_name AS
( first VARCHAR(30),
last VARCHAR(60)
);
CREATE TABLE telephone_m
( tnumber VARCHAR(15) NOT NULL UNIQUE
);
CREATE TABLE people
( curp CHAR(18) NOT NULL PRIMARY KEY,
pname t_name NOT NULL,
birth_date DATE NOT NULL,
telephone_m VARCHAR(15) REFERENCES telephone_m
);
CREATE TABLE clients
( curp CHAR(18) NOT NULL PRIMARY KEY,
cid SERIAL NOT NULL REFERENCES cards,
clocation VARCHAR(29)
) INHERITS (people);
CREATE TABLE cards
( cid BIGSERIAL NOT NULL PRIMARY KEY,
curp CHAR(18) NOT NULL REFERENCES clients,
trips SMALLINT,
distance NUMERIC,
points NUMERIC
);
CREATE TABLE drivers
( curp CHAR(18) NOT NULL PRIMARY KEY,
rfc CHAR(22) NOT NULL UNIQUE,
adress t_adress NOT NULL
) INHERITS (people);
I've tried in PgAdmin 4 making right-click on a new database -> CREATE Script, it opens Query Editor, I copy paste my code and execute it, but it returns:
ERROR: CREATE DATABASE cannot be executed from a function or multi-command string
SQL state: 25001
I've also tried using Query Tool directly from the PgAdmin tools menu with the same results.
The database is created just fine. But if you want to create object in the new DB, you have to connect to it. In any client, including pgAdmin4.
And you cannot run CREATE DATABASE inside of a transaction. Must be committed on it's own. Executing multiple commands at once is automatically wrapped into a single transaction in pgAdmin.
You have to execute CREATE DATABASE mydb; on its own (for instance by selecting only that line and pressing F5 while being connected to any DB, even the maintenance db "postgres". Then click on "Databases" in the object browser in the pgadmin4 main window / tab, hit F5 to refresh the view, click on the new DB, open up a new query tool with the flash icon (in a new window / tab) and execute the rest of your script there.
psql scripts manage by using the meta-command \c to connect to the new db after creating it, within the same session.
Asides:
"database" is no good name for a database.
CREATE TYPE AS (...), but just CREATE TABLE (...). No AS.
And you typically don't want to use the data type CHAR(18). See:
Any downsides of using data type "text" for storing strings?
Get sum of integers for UNIQUE ids
What is the overhead for varchar(n)?
Should I add an arbitrary length limit to VARCHAR columns?
There is the ; missing after the CREATE DATABASE database (and perhaps give the db a better name).

H2 Database fails to find existing column

My Configuration file:
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# Datasource
spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
my data.sql script is something like :
CREATE TABLE IF NOT EXISTS people (
ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
vname varchar(255) not null
);
INSERT INTO people(vname) VALUES ('Chuck Norris');
When this is executed, INSERT fails with error :
cannot find 'VNAME' column.
Why is the column name auto all capsed? does that affect my INSERT command?
I just created the table, why cant INSERT find vname column?
Did you perhaps already create the table PEOPLE without the VNAME column? Your SQL won't touch it if the table already exists. Remove the database files and try again...

Table <name> already exits Error (3010)

I am new to SQL and I am trying to run a CREATE TABLE query in Ms Access 2016 but I get an error saying that "mytablename" already exits which can't be true because I also ran a DROP TABLE "mytablename" query and I got an error saying "mytablename" does not exist. Please help. Point me in the right direction at least. Here is the CREATE TABLE query.
CREATE TABLE Team(
Team_ID AUTOINCREMENT UNIQUE NOT NULL,
Name VARCHAR(40) NOT NULL,
Origin VARCHAR(40) NOT NULL,
NetWorth CURRENCY NOT NULL,
PRIMARY KEY(Team_ID)
);
See check by VBA and check by SQL for check existence of your database.
If table exists you can recreate (drop and create again) table. Alternative way is to create table if table is not exist and do nothing if table exists.

Derby DB modify 'GENERATED' expression on column

I'm attempting to alter a Derby database that has a table like this:
CREATE TABLE sec_merch_categories (
category_id int NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
packageName VARCHAR(100) NOT NULL,
name VARCHAR(100) NOT NULL,
primary key(category_id)
);
I'd like to change the category_id column to be:
category_id int NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
The only place I've seen that documents this is IBM's DB2, which advises dropping the expression, changing the integrity of the table, and adding the expression back. Is there anyway of doing this in Derby?
Thanks,
Andrew
You can create a new table with the schema you want (but a different name), then use INSERT INTO ... SELECT FROM ... to copy the data from the old table to the new table (or unload the old table and reload it into the new table using the copy-data system procedures), then use RENAME TABLE to rename the old table to an alternate name and rename the new table to its desired name.
And, as #a_horse_with_no_name indicated in the above comment, all of these steps are documented in the Derby documentation on the Apache website.