Bulk Insert but the Primary Key is Null - sql

So I know that PK's can't be null, but I've been tasked with bulk inserting data from a .txt file(s) but the PK's in the files are NULL. I'm stumped and I don't actually know how to get around this.
The table creation:
CREATE TABLE BILLING (
FolioBillingID smallint NOT NULL PRIMARY KEY,
FolioID smallint NOT NULL FOREIGN KEY REFERENCES
FOLIO(FolioID),
BillingCategoryID smallint NOT NULL FOREIGN KEY REFERENCES
BILLINGCATEGORY(BillingCategoryID),
BillingDescription char(30) NOT NULL,
BillingAmount smallmoney NOT NULL,
BillingItemQty tinyint NOT NULL,
BillingItemDate date NOT NULL)
Here's an example from the .txt file I need to insert:
|1|1|Room|99|1|5/2/2018
|1|2|Lodging Tax|11.14|1|5/2/2018
|1|1|Room|99|1|5/3/2018
And this is how I'm trying to bulk insert:
BULK INSERT BILLING FROM 'c:\stage\farms1-1\Billing.txt'
WITH (FIELDTERMINATOR='|', FIRSTROW=1)
Is there a way around this? And if so, how would I go about it?
Any help would be greatly appreciated! :)

Make FolioBillingID autoincrement

Related

Syntax error in CREATE TABLE statement - SQL (MS Access 2016)

I took this example from my class textbook and pretty much copied word for word from the text. The following is the code that I wrote into MS Access:
CREATE TABLE PRODUCT(
P_CODE VARCHAR(10) NOT NULL UNIQUE,
P_DESCRIPT VARCHAR(35) NOT NULL,
P_INDATE DATE NOT NULL,
P_QOH SMALLINT NOT NULL,
P_MIN SMALLINT NOT NULL,
P_PRICE NUMBER(8, 2) NOT NULL,
P_DISCOUNT NUMBER(5, 2) NOT NULL,
V_CODE INTEGER,
PRIMARY KEY (P_CODE),
FOREIGN KEY (V_CODE) REFERENCES VENDOR ON UPDATE CASCADE
);
This code produces a syntax error every time it's run within MS Access.
I tried running this query to create the table PRODUCT within my db. When reviewing the code, I couldn't find anything specific that would have caused the error, but I could be wrong due to my inexperience with SQL.
Any help would be greatly appreciated!
Per the comments the problem is the Decimal type. I'm updating the answer here for Access 2016: How do I create a decimal field in Access with Alter Table?
First enable the SQL Ansi 92 standard. In 2016 this has moved to File-Options-Object Designers-Query Design. It seems you can only enable it for new databases. So do so and create a new database then open the sql-tab of a blank query and paste the following code:
'make sure you have a VENDOR table first for instance:
CREATE TABLE VENDOR
(V_CODE AutoIncrement CONSTRAINT PrimaryKEY PRIMARY KEY);
'Then with slightly less old syntax (varchar would usually be text, smallint would usually be integer with a size, and PrimaryKey includes Not null and unique)
CREATE TABLE PRODUCTS(
P_CODE VARCHAR(10) CONSTRAINT PrimaryKey PRIMARY KEY,
P_DESCRIPT VARCHAR(35) NOT NULL,
P_INDATE DATE NOT NULL,
P_QOH SMALLINT NOT NULL,
P_MIN SMALLINT NOT NULL,
P_PRICE DECIMAL(8, 2) NOT NULL,
P_DISCOUNT DECIMAL(5, 2) NOT NULL,
V_CODE LONG REFERENCES VENDOR(V_CODE)
);
'Alter Table also works now
ALTER TABLE PRODUCTS ADD COLUMN P_PRICE DECIMAL(8,2) NOT NULL;
Caveat
At least the sql-pane tells you that something in your DDL is wrong if not what. if you are not using the default Jet database as your backend then you are stuck concatenating strings using vba and ADO according to here: https://learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/create-table-statement-microsoft-access-sql
At that point I would manually try manually adding the decimal columns if there where not too many.

ORA-02291 parent key not found, first

My first programming program is an Oracle Database graduate certificate program, and the textbook is not Oracle friendly in some places (it is a generic database textbook). I had to rewrite the CREATE table commands and what I came up with is written below.
The tables are created in my database, and I can insert values into the vendor table; however, every time I insert values into the product table I receive the ORA-02291 integrity error.
I realize that the parent key is not being found in the vendor table, but I am at a loss as to why. I have tried a combination of column and table constraints on both tables, and nothing works. If someone could help me set up this relationship so I can practice that would be great!
CREATE TABLE VENDOR(
V_CODE INTEGER NOT NULL CONSTRAINT VENDOR_P_K PRIMARY KEY,
V_NAME VARCHAR(35) NOT NULL,
V_CONTACT VARCHAR(25) NOT NULL,
V_AREACODE CHAR(3) NOT NULL,
V_PHONE CHAR(8) NOT NULL,
V_STATE CHAR(2) NOT NULL,
V_ORDER CHAR(1) NOT NULL
);
----------------------------------------------------------------------------
CREATE TABLE PRODUCT(
P_CODE VARCHAR2(10) CONSTRAINT PRODUCT_P_CODE_PK PRIMARY KEY,
P_DESCRIPT VARCHAR2(35) NOT NULL,
P_INDATE DATE NOT NULL,
P_QOH NUMBER NOT NULL,
P_MIN NUMBER NOT NULL,
P_PRICE NUMBER(8,2) NOT NULL,
P_DISCOUNT NUMBER(5,2) NOT NULL,
V_CODE INTEGER NOT NULL,
CONSTRAINT V_CODE_FK FOREIGN KEY (V_CODE) REFERENCES VENDOR (V_CODE)
);
EDIT
INSERT INTO VENDOR 2
VALUES (21225, 'Bryson, Inc.', 'Smithson', '615','223-3234','TN','Y');
INSERT INTO VENDOR 2
VALUES (21226,'Superloo, Inc.','Flushing','904','215-8995','FL','N');
INSERT INTO PRODUCT 2
VALUES ('11QER/31','Power painter, 15 psi., 3-nozzle','03-Nov-13',8,5,109.99,0.00,25595);
The relationship is set up correctly.
You can only insert foreign key values matching a primary key value in the master table. In your example, you are inserting a product with V_CODE = 25595 but you are never inserting a vendor with this V_CODE.
Maybe you intended to insert the vendor later. This does not work, as the database is enforcing the constraints for every command. Therefore, insert the vendor first and append his products later.
If you want to delete vendors, first delete its products, then delete the vendor unless you are using Foreign Keys with Cascade Delete.

How do I insert data into a row in SQL?

I am following a tutorial and learning MVC from a book, where I was told to create a table using this script, which I did. But now I want to add an entire row to my Pet table, but I am unable to do it.
Script used to create all my tables.
CREATE TABLE [dbo].[Setting] (
[Id] INT NOT NULL IDENTITY(1, 1)
,[Key] VARCHAR(50) NOT NULL
,[Value] VARCHAR(500) NULL
,CONSTRAINT [PK_Setting] PRIMARY KEY ([Id])
);
CREATE TABLE [dbo].[PetType] (
[PetTypeID] INT NOT NULL IDENTITY(1, 1)
,[PetTypeDescription] VARCHAR(50) NULL
,CONSTRAINT [PK_PetType] PRIMARY KEY ([PetTypeID])
);
CREATE TABLE [dbo].[Status] (
[StatusID] INT NOT NULL IDENTITY(1, 1)
,[Description] VARCHAR(50) NOT NULL
,CONSTRAINT [PK_Status] PRIMARY KEY ([StatusID])
);
CREATE TABLE [dbo].[Pet] (
[PetID] INT NOT NULL IDENTITY(1, 1)
,[PetName] VARCHAR(100) NOT NULL
,[PetAgeYears] INT NULL
,[PetAgeMonths] INT NULL
,[StatusID] INT NOT NULL
,[LastSeenOn] DATE NULL
,[LastSeenWhere] VARCHAR(500) NULL
,[Notes] VARCHAR(1500) NULL
,[UserId] INT NOT NULL
,CONSTRAINT [PK_Pet] PRIMARY KEY ([PetID])
,CONSTRAINT [FK_Pet_Status] FOREIGN KEY ([StatusID]) REFERENCES [Status]([StatusID])
,CONSTRAINT [FK_Pet_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
CREATE TABLE [dbo].[PetPhoto] (
[PhotoID] INT NOT NULL IDENTITY(1, 1)
,[PetID] INT NOT NULL
,[Photo] VARCHAR(500) NOT NULL CONSTRAINT [DF_PhotoFile] DEFAULT '/content/pets/no-image.png'
,[Notes] VARCHAR(500) NULL
,CONSTRAINT [PK_PetPhoto] PRIMARY KEY ([PhotoID])
,CONSTRAINT [FK_PetPhoto_Pet] FOREIGN KEY ([PetID]) REFERENCES [Pet]([PetID])
);
CREATE TABLE [dbo].[Message] (
[MessageID] INT NOT NULL
,[UserId] INT NOT NULL
,[MessageDate] DATETIME NOT NULL
,[From] VARCHAR(150) NOT NULL
,[Email] VARCHAR(150) NOT NULL
,[Subject] VARCHAR(150) NULL
,[Message] VARCHAR(1500) NOT NULL
,CONSTRAINT [PK_Message] PRIMARY KEY ([MessageID])
,CONSTRAINT [FK_Message_User] FOREIGN KEY ([UserId]) REFERENCES [UserProfile]([UserId])
);
I want to add some random values(for testing) into my Pet table's first row.
This is the Pet table's first row as an image for further clarity.
I tried using this script to add values to my table.
INSERT INTO Pet VALUES ('1', 'Fido', '12', '4', '1', '12/07/2004', 'New York', 'nothing', '1')
But I got an error saying
An explicit value for the identity column in table 'Pet' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Now I am fairly new to SQL and I am unable to figure this out. I looked at other SO answers where people said something about SET IDENTITY_INSERT, but this didn't work for me as well. I believe I misunderstood other SO answer since I am fairly new to database languages. So need your help.
Thanks
In SQL Server identity is used for autoincrement. identity(1,1) means the starting value for the column will be 1 and will be incremented by 1. You can change it to desired value for example identity(5,2) starts the value at 5 and increments by 2. You no need to specify an explicit value for setting this column, it will be automatically assigned a unique value.
In mysql you can use AUTO_INCREMENT
Refer w3schools page for details sql autoincrement
PetID is defined as IDENTITY so you cannot specify a value to INSERT in that column unless you set "IDENTITY_INSERT" option to ON.
You have two options:
Dont specify that column/value and let SQL generate it for you.
Set IDENTITY_INSERT to ON before your INSERT operation.
Another very cool way to add rows/edit table (including editting deleting rows) is to use Microsoft SQL Management Studio Express. I didn't know about this until I'd been learning SQL for years. Basically expand the tree structure to the left, right-click on a table and choose Edit Table. When you get going with SQL more, you can edit Stored Procedures in here and pretty much anything SQL else you can can think of.
I've blurred out the actual database names but this gives you the gist of it :-

Are these FKs necessary -- and are they stopping me?

I'm having some difficulties with a database I'm creating for a summer camp, specifically with the PK and FK constraints. When I declare the FK constraint (e.g. FOREIGN KEY(PID) references Campers(CamperID)) I get an error running my code through pgAdmin (I'm using PostgreSQL). I understand that, for example, the Campers table is not yet created, and this is most likely part/all of the roadblock, however I feel like my FKs are still wrong somehow. To my understanding, a FK is a PK in another table -- but I feel like there is some redundancy or disconnect between my tables.
I've put the syntax for some of my CREATE statements below. I'm not sure if I'll get reprimanded for the quality of my (somewhat vague) question, but I feel a bit lost and would appreciate any help or advice. Thank you in advance!
DROP TABLE IF EXISTS People;
CREATE TABLE People (
PID VARCHAR(10) NOT NULL UNIQUE,
FName TEXT NOT NULL,
LName TEXT NOT NULL,
DOB DATE NOT NULL,
ArrivalDate DATE NOT NULL DEFAULT CURRENT_DATE,
DepartureDate DATE,
US_PhoneNum VARCHAR(11) NOT NULL,
StreetAddress VARCHAR(200) NOT NULL,
Sex GENDER NOT NULL,
ZIP VARCHAR(10) NOT NULL,
PRIMARY KEY(PID),
FOREIGN KEY(PID) REFERENCES Campers(CamperID),
FOREIGN KEY(PID) REFERENCES Counselors(CounselorID),
FOREIGN KEY(ZIP) REFERENCES Zip(ZIP)
);
DROP TABLE IF EXISTS Zip;
CREATE TABLE Zip (
ZIP VARCHAR(10) NOT NULL,
City TEXT NOT NULL,
State VARCHAR(2) NOT NULL,
PRIMARY KEY(ZIP)
);
DROP TABLE IF EXISTS Campers;
CREATE TABLE Campers (
CamperID VARCHAR(10) NOT NULL REFERENCES People(PID),
AgeGroup AGES NOT NULL,
CabinID VARCHAR(2) NOT NULL,
Bed BEDTYPES NOT NULL,
GroupID VARCHAR(3) NOT NULL,
PRIMARY KEY(CamperID),
FOREIGN KEY(CamperID) REFERENCES People(PID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID),
FOREIGN KEY(Bed) REFERENCES Beds(Bed),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID)
);
DROP TABLE IF EXISTS Counselors;
CREATE TABLE Counselors (
CounselorID VARCHAR(10) NOT NULL REFERENCES People(PID),
GroupID VARCHAR(3) NOT NULL,
CabinID VARCHAR(2) NOT NULL,
PRIMARY KEY(CounselorID),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID)
);
ERROR message for further clarification:
ERROR: relation "campers" does not exist
********** Error **********
ERROR: relation "campers" does not exist
SQL state: 42P01
There are more tables (obviously) which I can provide the create statements for, if needed.
You should really start here: Foreign key.
In the context of relational databases, a foreign key is a field (or
collection of fields) in one table that uniquely identifies a row of
another table.
What you are trying to do in your script is to create a circular link between People, Campers and Counselors. Having a Primary Key field also a Foreign Key mandates that IDs across all referenced tables are identical.
... and to create a Foreign Key the referenced table must already exist in the database. So you should start with the table that does not have any Foreign Keys and create tables that reference only those tables created previously. Alternatively you can create all tables without Foreign Keys and add them later, when all the tables are present.
... and to answer the question, Foreign Keys are never necessary, but they might help.

Error creating table in oracle

I am trying to create a table in oracle but I am getting this error: unknown command ")" - rest of line ignored. I can't figure out what is causing this error. Below is my SQL for the table:
CREATE TABLE PAYMENT
(PayNum INT NOT NULL PRIMARY KEY,
CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PDate DATE NOT NULL,
Amt DECIMAL(11,2) NOT NULL,
CONSTRAINT fk_BANKACC_PAYMENT FOREIGN KEY (BankName, AccNum)
REFERENCES BANKACC(BankName, AccNum),
CONSTRAINT fk_CRCARD_PAYMENT FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD(CType, CCNum)
);
Your code is correct. Make sure you are referencing primary keys (all 4).
Check this: http://sqlfiddle.com/#!2/7be70/1/0
If you do not follow that, you may get this error: There are no primary or candidate keys in the referenced table 'BANKACC' that match the referencing column list in the foreign key 'fk_BANKACC_PAYMENT'.
Code in the fiddle above:
CREATE TABLE BANKACC
(BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PRIMARY KEY(BankName, AccNum));
CREATE TABLE CRCARD
(CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
PRIMARY KEY(CType, CCNum));
CREATE TABLE PAYMENT
(PayNum INT NOT NULL PRIMARY KEY,
CType VARCHAR(1) NOT NULL,
CCNum VARCHAR(16) NOT NULL,
BankName VARCHAR(75) NOT NULL,
AccNum INT NOT NULL,
PDate DATE NOT NULL,
Amt DECIMAL(11,2) NOT NULL,
CONSTRAINT fk_BANKACC_PAYMENT FOREIGN KEY (BankName, AccNum)
REFERENCES BANKACC(BankName, AccNum),
CONSTRAINT fk_CRCARD_PAYMENT FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD(CType, CCNum)
);
Also you should read this for better understanding on how to implement foreign key constraint: http://docs.oracle.com/cd/E17952_01/refman-5.5-en/create-table-foreign-keys.html
If you're running this in SQL*Plus, get rid of the blank line between REFERENCES and ):
REFERENCES CRCARD(CType, CCNum)
);
Or set sqlblanklines on to change the behaviour.
By default it interprets a blank line as the end of the statement, but doesn't run it. So your entire CREATE TABLE command is essentially ignored, and the ); is treated as a stanalone command. Hence the error message you get, since it doesn't mean anything on its own.
Please use NUMBER for numeric columns.
http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT313
Also, in Oracle, use VARCHAR2 for strings.
but of it your syntax should be correct.