How do I insert data into a row in SQL? - 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 :-

Related

Creating SQL database. with multiple primary and foreign keys

I'm currently working through an assignment that is asking me to create a SQL database using SQL Server Express. This is what it's asking for:
CREATE DATABASE USING SQL
And this is the code I have tried running;
CREATE DATABASE db_Library
Go
USE db_Library
CREATE TABLE tbl_library_branch
(
library_branch_branch_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_branch_branch_name VARCHAR(50) NOT NULL,
library_branch_address VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_publisher
(
library_publisher_publisher_name VARCHAR(50) PRIMARY KEY NOT NULL,
library_publisher_address VARCHAR(50) NOT NULL,
library_publisher_phone INT NOT NULL
);
CREATE TABLE tbl_books
(
library_books_book_id INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_books_title VARCHAR(50) NOT NULL,
library_books_publisher_name VARCHAR(50) NOT NULL CONSTRAINT fk_library_books_publisher_name FOREIGN KEY REFERENCES tbl_publisher(library_publisher_publisher_name) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE tbl_book_authors
(
library_book_authors_book_id INT NOT NULL CONSTRAINT fk_library_book_authors_book_id FOREIGN KEY REFERENCES tbl_books(library_books_book_id) ON UPDATE CASCADE ON DELETE CASCADE,
library_book_authors_author_name VARCHAR(50) NOT NULL
);
CREATE TABLE tbl_book_copies
(
library_book_copies_book_id INT NOT NULL CONSTRAINT fk_library_book_copies_book_id FOREIGN KEY REFERENCES tbl_books(library_books_title),
library_book_copies_branch_id INT NOT NULL,
library_book_copies_number_of_copies INT NOT NULL
);
CREATE TABLE tbl_book_loans
(
library_book_loans_book_id INT NOT NULL,
library_book_loans_branch_id INT NOT NULL,
library_book_loans_card_no INT NOT NULL,
library_book_loans_date_out INT NOT NULL,
library_book_loans_date_due INT NOT NULL
);
CREATE TABLE tbl_borrower
(
library_borrower_card_no INT PRIMARY KEY NOT NULL IDENTITY (1,1),
library_borrower_name VARCHAR(50) NOT NULL,
library_borrower_address VARCHAR(50) NOT NULL,
library_borrower_phone VARCHAR(50) NOT NULL
);
Using the library "Books" as an example it looks like I need to have BoodID as a primary key and Title as a primary key, but you can't have more than one primary key per table..
Then I have to take BookID from the Book_Copies table and the Book_Loans table connect to the primary key of Title in Books?
I'm beyond stuck at this point and would appreciate any resources you think could help.
There is no need to be so verbose. I think you want something more like this (for two tables):
CREATE TABLE tbl_publisher (
publisher_id int IDENTITY(1, 1) PRIMARY KEY,
publisher_name VARCHAR(50) NOT NULL UNIQUE,
address VARCHAR(50) NOT NULL,
phone INT NOT NULL
);
CREATE TABLE books (
book_id INT IDENTITY (1,1) PRIMARY KEY,
title VARCHAR(50) NOT NULL UNIQUE,
publisher_id INT NOT NULL CONSTRAINT fk_books_publisher__id FOREIGN KEY REFERENCES tbl_publisher(publisher_id) ON UPDATE CASCADE ON DELETE CASCADE
);
Notes:
Stick with synthetic primary keys for all the tables. That is, identity columns.
Other columns can be declared to be unique. That is fine.
I type quite fast. And yet I would quickly wary of typing library_book_ over and over. Such repetition just makes it harder to write and read queries.

VB.Net Create a table programatically with foreign key

I'm trying to create a table programmatically via VB.Net and two of the columns should have a primary key. I have the following T-SQL code and I basically need to translate it to SQL so I can execute it programmatically via vb.net :
CREATE TABLE [dbo].[Orders]
(
[OrderID] INT IDENTITY (1, 1) NOT NULL,
[FoodID] INT NOT NULL,
[PriceID] INT NOT NULL,
PRIMARY KEY CLUSTERED ([OrderID] ASC),
CONSTRAINT [FK_Orders_Customer]
FOREIGN KEY ([FoodID]) REFERENCES [dbo].[Customer] ([FoodID])
)
This is what I currently have for my vb.net sql code:
CREATE TABLE customer(OrderID INT NOT NULL,FoodID INT NOT NULL ,PriceID INT NOT NULL
Now I'm not sure how to declare the primary key and how to declare the foreign keys. Also if someone would show an example on how to declare a composite key I would also be grateful (ie. OrderID and FoodID both primary keys). Thank you.

Create table with UNIQUEIDENTIFIER as PK

I have been trying (unsuccessfully) to create a table with a UNIQUEIDENTIFIER as the primary key. The script below will create the table just fine, however there is no PK specified. This is my first time using a UNIQUEIDENTIFIER, however. Any ideas?
T-SQL
CREATE TABLE [dbo].[AgentRelationshipCodes]
(
Id UNIQUEIDENTIFIER NOT NULL DEFAULT NEWID(),
RelationshipId char(3) NULL,
EffectiveDate datetime NULL,
LastChangeDate datetime NOT NULL,
LastChangeId char(6) NOT NULL,
AgtTableId int FOREIGN KEY REFERENCES AgentTransmission(ID)
);
Management Studio
create table [dbo].[AgentRelationshipCodes]
(
Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT NEWID(),
.
.
.
)
Repeat for the other tables.
Answered here by Christian Hayter

SQL define table for treelike structure

In previous versions of Visual studio there was a way to build DB using diagrams.
In 2012 they took out that possibility.
I need to create script which creates table for category tree.
CREATE TABLE [dbo].[Categories]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NVARCHAR(50) NOT NULL,
[ParentId] INT NOT NULL DEFAULT 0,
[FK_Parent] int FOREIGN KEY ([ParentId]) REFERENCES [Categories]([Id]) NOT NULL
)
If I create table like this, I cannot add top level records.
Define top-level records as having a NULL FK_Parent. Just change your definition to allow nulls.
CREATE TABLE [dbo].[Categories]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NVARCHAR(50) NOT NULL,
[ParentId] INT NOT NULL ,
---llow NULL FK_Parent for top-level
CONSTRAINT [FK_Parent] FOREIGN KEY ([ParentId]) REFERENCES [Categories]([Id])
)

Multilingual database design

I'm trying to design a database schema for a multilingual application. I have so far found a sample from this address. http://fczaja.blogspot.com/2010/08/multilanguage-database-design.html
But I haven't understood this sample. Should I insert Id value on app_product first? How can I know that these values are true for ProductId on app_product_translation?
CREATE TABLE ref_language (
Code Char(2)NOT NULL,
Name Varchar(20) NOT NULL,
PRIMARY KEY (Code)
);
CREATE TABLE app_product (
Id Int IDENTITY NOT NULL,
PRIMARY KEY (Id)
);
CREATE TABLE app_product_translation (
ProductId Int NOT NULL,
LanguageCode Char(2) NOT NULL,
Description Text NOT NULL,
FOREIGN KEY (ProductId) REFERENCES app_product(Id),
FOREIGN KEY (LanguageCode) REFERENCES ref_language(Code)
);
It looks like SQLServer code, proceeding on that assumption.
Yes you must insert the app_product first. But you cannot insert the id column's value. It is assigned automatically, because it is an identity column.
Two things you can check out...to find the identity column's value after inserting.
The OUTPUT clause of the INSERT statement. It can return any values that are inserted, not just the identity column.
The ##Identity variable. (by far more traditional and popular)
declare #lastid int
insert into x values (1,2,3)
set #lastid = ##identity
insert into y values (#lastid, a, b, c)