SQL Creating a table - sql

Im trying to create a table called "Receita" which contains a foreign key from a table called Farmaco
but for reason i keep getting this error and im not really picking it up
"There is already an object named 'Farmaco' in the database."
heres the cod where i create both tables
if not exists (select * from dbo.sysobjects
where id = object_id(N'[dbo].[Receita]'))
begin
CREATE TABLE Receita(
IDReceita int NOT NULL
CHECK(IDReceita>0),
IDFarmaco int,
CONSTRAINT PK_IDReceita PRIMARY KEY (IDReceita),
CONSTRAINT FK_IDFarmaco FOREIGN KEY (IDFarmaco)
REFERENCES Farmaco (IDFarmaco)
ON UPDATE CASCADE,
);
end
and
if not exists (select * from dbo.sysobjects
where id=object_id(N'[dbo.Farmaco]'))
begin
CREATE TABLE Farmaco(
IDFarmaco int NOT NULL
CHECK(IDFarmaco>0),
IDMedico int,
Tipo varchar(50)
CONSTRAINT PK_IDFarmaco PRIMARY KEY (IDFarmaco),
CONSTRAINT FK_IDMedico7 FOREIGN KEY (IDMedico)
REFERENCES Médico (IDMedico)
ON UPDATE CASCADE,
);
end
Thank you

Like SteveJ mentioned there's a mistake here:
if not exists (
select * from dbo.sysobjects where id=object_id(N'[dbo.Farmaco]')
)
, which should be
if not exists (
select * from dbo.sysobjects where id=object_id(N'[dbo].[Farmaco]')
)
Look at brackets around the table name!
So the problem is that in the second script if condition is always true even when Farmaco table exists. Because of that you keep getting error message.

i have seen your snippet, you have to create table "dbo.Farmaco" first before "dbo.Receita" thats only way you can reference dbo.Farmaco table as foreign key in
dbo.Receita table.
Hope this will help you.

Related

How to fix the trigger with check compiler log error?

Please, help!
I have trigger:
CREATE TRIGGER check_reservation BEFORE INSERT ON order
FOR EACH ROW
DECLARE mistake INTEGER;
BEGIN
SELECT count(*) INTO mistake FROM order join reserving
on id_order = reserving.order_id_order
WHERE reserving.room_num_room=:new.room_num_room
AND (order.reservation_from < :new.reservation_from AND :new.reservation_from < order.reservation_to) OR
(order.reservation_from < :new.reservation_from AND :new.reservation_to < order.reservation_to) OR
(:new.reservation_from <= order.reservation_from AND order.reservation_to <= :new.reservation_to);
IF mistake>0 THEN
raise_application_error(-20001,'reservation already exists');
END IF;
END;
The idea of the trigger is not to allow make a reservation on already booked room. When I run it I had check compiler log error message. How can I change trigger?
I have following tables:
CREATE TABLE order (
id_order CHAR(100) NOT NULL,
reservation_from DATE NOT NULL,
reservation_to DATE NOT NULL,
);
ALTER TABLE order ADD CONSTRAINT order_pk PRIMARY KEY ( id_order );
CREATE TABLE room (
num_room CHAR(100) NOT NULL,
type VARCHAR2(100) NOT NULL,
);
ALTER TABLE room ADD CONSTRAINT room_pk PRIMARY KEY ( num_room );
CREATE TABLE reserving (
room_num_room CHAR(100) NOT NULL,
order_id_order CHAR(100) NOT NULL
);
ALTER TABLE reserving ADD CONSTRAINT reserving_pk PRIMARY KEY ( room_num_room,
order_id_order );
ALTER TABLE reserving
ADD CONSTRAINT reserving_order_fk FOREIGN KEY ( order_id_order )
REFERENCES order ( id_order );
ALTER TABLE reserving
ADD CONSTRAINT reserving_room_fk FOREIGN KEY ( room_num_room )
REFERENCES room ( num_room );
I tried recreating the trigger with the statements above. The statements failed with several errors, it looks as if they were not tested before posting them as question. Please take some time posting a quality question.
Example:
CREATE TABLE room (
num_room CHAR(100) NOT NULL,
type VARCHAR2(100) NOT NULL, << this trailing comma makes this statement fail.
);
After fixing all errors I ran the "CREATE TRIGGER" and it errored out with
PLS-00049: bad bind variable 'NEW.ROOM_NUM_ROOM'
That is because the column ROOM_NUM_ROOM does not exist in the "ORDER" table.
If I remove the reference to 'NEW.ROOM_NUM_ROOM' the trigger compiles successfully.
However, as gsalem pointed out, this will not work because it will raise a mutating table error. In the trigger code you cannot execute DML referencing the table that the trigger is on. There is plenty of documentation on how to avoid mutating table errors.

Remove Unique constraint on a column in sqlite database

I am trying to remove a UNIQUE constraint on a column for sqlite but I do not have the name to remove the constraint. How can I find the name of the UNIQUE constraint name to remove it.
Below is the schema I see for the table I want to remove the constraint
UNIQUE (datasource_name)
sqlite> .schema datasources
CREATE TABLE "datasources" (
created_on DATETIME NOT NULL,
changed_on DATETIME NOT NULL,
id INTEGER NOT NULL,
datasource_name VARCHAR(255),
is_featured BOOLEAN,
is_hidden BOOLEAN,
description TEXT,
default_endpoint TEXT,
user_id INTEGER,
cluster_name VARCHAR(250),
created_by_fk INTEGER,
changed_by_fk INTEGER,
"offset" INTEGER,
cache_timeout INTEGER, perm VARCHAR(1000), filter_select_enabled BOOLEAN, params VARCHAR(1000),
PRIMARY KEY (id),
CHECK (is_featured IN (0, 1)),
CHECK (is_hidden IN (0, 1)),
FOREIGN KEY(created_by_fk) REFERENCES ab_user (id),
FOREIGN KEY(changed_by_fk) REFERENCES ab_user (id),
FOREIGN KEY(cluster_name) REFERENCES clusters (cluster_name),
UNIQUE (datasource_name),
FOREIGN KEY(user_id) REFERENCES ab_user (id)
);
SQLite only supports limited ALTER TABLE, so you can't remove the constaint using ALTER TABLE. What you can do to "drop" the column is to rename the table, create a new table with the same schema except for the UNIQUE constraint, and then insert all data into the new table. This procedure is documented in the Making Other Kinds Of Table Schema Changes section of ALTER TABLE documentation.
I just ran into this myself. An easy solution was using DB Browser for SQLite
It let me remove a unique constraint with just a checkbox in a gui.
PRAGMA foreign_keys=off;
BEGIN TRANSACTION;
ALTER TABLE table_name RENAME TO old_table;
CREATE TABLE table_name
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
);
INSERT INTO table_name SELECT * FROM old_table;
COMMIT;
PRAGMA foreign_keys=on;
Source: https://www.techonthenet.com/sqlite/unique.php
I was just working through this issue on a small database and found it easier to dump the data as SQL statements, it prints out your tables exactly as they are and also adds the INSERT INTO statements to rebuild the DB.
The .help terminal command shows:
.dump ?OBJECTS? Render database content as SQL
and prints the SQL to the terminal, you can update it in a TXT file. For once off changes and tidying this seems like a reasonable solution albeit a little inelegant

Microsoft Access - Enter Parameter Value why?

I am encountering a problem for my database.
And tried to do the query for how many transactions have movie "Harry_Potter"?
so I used SQL query:
SELECT
COUNT(td.movie) AS number_of_occurrence,
td.transaction_number
FROM
TransactionDetails td,
MovieDetails md
WHERE
md.movie = Harry_Potter
But it asks for Harry_Potter enter parameter value why?
The relevant SQL statements are
CREATE TABLE TransactionDetails
(
transaction_number INTEGER PRIMARY KEY,
movie VARCHAR(30) NOT NULL,
date_of_transaction DATE NOT NULL,
member_number INTEGER NOT NULL
)
CREATE TABLE MovieDetails
(
movie VARCHAR(30) PRIMARY KEY,
movie_type VARCHAR(3) NOT NULL,
movie_genre VARCHAR(10) NOT NULL
)
ALTER TABLE TransactionDetails
ADD CONSTRAINT member_number_fk FOREIGN KEY (member_number) REFERENCES LimelightMemberDetails(member_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT transaction_number_drink_fk FOREIGN KEY (transaction_number) REFERENCES DrinkTransactionDetails(transaction_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT transaction_number_food_fk FOREIGN KEY (transaction_number) REFERENCES FoodTransactionDetails(transaction_number);
ALTER TABLE TransactionDetails
ADD CONSTRAINT movie_fk FOREIGN KEY (movie) REFERENCES MovieDetails (movie);
Thank you for your help! If there is anything wrong with my database design please let me know! thank you!
Change the query to something like
SELECT
COUNT(td.movie) AS number_of_occurrence,
td.transaction_number
FROM
TransactionDetails td,
MovieDetails md
WHERE
md.movie = "Harry_Potter"
Seeing as movie is a string, you need quotes around the value you are looking for.
If I am not mistaken MS Access takes " and SQL SERVER takes '
try this
md.movie = "Harry_Potter"
I guess, you are simply missing the quotation marks around the string you are comparing.

Can these three SQLITE INSERTS be combinded or improved?

I have three tables:
CREATE TABLE "local" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "serialNumber" TEXT, "location" TEXT)
CREATE TABLE "setups" ("id" INTEGER PRIMARY KEY NOT NULL ,"hold" TEXT,"mode" INTEGER,"setTemp" REAL,"maxSTemp" REAL,"minSTemp" REAL,"units" TEXT,"heat" INTEGER,"heatMode" INTEGER,"fanMode" INTEGER,"fan" INTEGER,"cool" INTEGER)
CREATE TABLE "data" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"humidity" REAL,"time" INTEGER,"filtChng" INTEGER,"indoorTemp" REAL,"outdoorTemp" REAL, "setups_id" INTEGER, "local_id" INTEGER)
Everytime I get a new entry I execute:
INSERT INTO local ('serialNumber') SELECT 'XXXX' WHERE NOT EXISTS (SELECT * FROM local WHERE serialNumber='XXXX')"
INSERT INTO setups ('hold','mode','setTemp','maxSTemp','minSTemp','units','heat','heatMode','fanMode','fan','cool') SELECT '00',1,74.0,74.0,74.0,'F',1,1,1,1,1 WHERE NOT EXISTS (SELECT * FROM setups WHERE hold='00' AND mode=1 AND setTemp=74.0 AND maxSTemp=74.0 AND minSTemp=74.0 AND units='F' AND heat=1 AND heatMode=1 AND fanMode=1 AND fan=1 AND cool=1)
INSERT INTO data ('humidity','filtChng','time','indoorTemp','outdoorTemp',local_id,setups_id) SELECT 74.0,111111111,100,74.0,74.0,local.id,setups.id FROM local CROSS JOIN setups WHERE local.serialNumber='XXXX' AND setups.hold='00' AND setups.mode=1 AND setups.setTemp=74.0 AND setups.maxSTemp=74.0 AND setups.minSTemp=74.0 AND setups.units='F' AND setups.heat=1 AND setups.heatMode=1 AND setups.fanMode=1 AND setups.fan=1 AND setups.cool=1
What I am doing works, but seems slow and redundant/inefficient...
Well, you can remove the "where not exists" part from the "local" insert if you use a unique constraint on the "serialNumber" field. Be careful, this will throw a constraint violation instead of just not inserting the row. So be sure to handle that in the application.
And though I assume it is, be sure that checking for duplicates is really necessary in your app.

SQL Server 2005: Nullable Foreign Key Constraint

I have a foreign key constraint between tables Sessions and Users. Specifically, Sessions.UID = Users.ID. Sometimes, I want Sessions.UID to be null. Can this be allowed? Any time I try to do this, I get an FK Constraint Violation.
Specifically, I'm inserting a row into Sessions via LINQ. I set the Session.User = null; and I get this error:
An attempt was made to remove a relationship between a User and a Session. However, one of the relationship's foreign keys (Session.UID) cannot be set to null.
However, when I remove the line that nulls the User property, I get this error on my SubmitChanges line:
Value cannot be null.
Parameter name: cons
None of my tables have a field called 'cons', nor is it in my 5,500-line DataContext.designer.cs file, nor is it in the QuickWatch for any of the related objects, so I have no idea what 'cons' is.
In the Database, Session.UID is a nullable int field and User.ID is a non-nullable int. I want to record sessions that may or may not have a UID, and I'd rather do it without disabling constraint on that FK relationship. Is there a way to do this?
I seemed to remember creating a nullable FK before, so I whipped up a quick test. As you can see below, it is definitely doable (tested on MSSQL 2005).
Script the relevant parts of your tables and constraints and post them so we can troubleshoot further.
CREATE DATABASE [NullableFKTest]
GO
USE [NullableFKTest]
GO
CREATE TABLE OneTable
(
OneId [int] NOT NULL,
CONSTRAINT [PK_OneTable] PRIMARY KEY CLUSTERED
(
[OneId] ASC
)
)
CREATE TABLE ManyTable (ManyId [int] IDENTITY(1,1) NOT NULL, OneId [int] NULL)
GO
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_ManyTable_OneTable]') AND parent_object_id = OBJECT_ID(N'[dbo].[ManyTable]') )
ALTER TABLE [dbo].[ManyTable] WITH CHECK ADD CONSTRAINT [FK_ManyTable_OneTable] FOREIGN KEY([OneId])
REFERENCES [dbo].[OneTable] ([OneId])
GO
--let's get a value in here
insert into OneTable(OneId) values(1)
select* from OneTable
--let's try creating a valid relationship to the FK table OneTable
insert into ManyTable(OneId) values (1) --fine
--now, let's try NULL
insert into ManyTable(OneId) values (NULL) --also fine
--how about a non-existent OneTable entry?
insert into ManyTable(OneId) values (5) --BOOM! - FK violation
select* from ManyTable
--1, 1
--2, NULL
--cleanup
ALTER TABLE ManyTable DROP CONSTRAINT FK_ManyTable_OneTable
GO
drop TABLE OneTable
GO
drop TABLE ManyTable
GO
USE [Master]
GO
DROP DATABASE NullableFKTest