INSERT INTO many-to-many table with existing rows - sql

I'm currently merging two databases to one and facing a problem with a many-to-many table.
I got the following SQL structure:
CREATE TABLE [dbo].[Module] (
ModuleID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name VARCHAR(50) NOT NULL
)
CREATE TABLE [dbo].[Message] (
MessageID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name VARCHAR(50) NOT NULL,
Size INT NOT NULL
)
CREATE TABLE [dbo].[Bind] (
ModuleID INT FOREIGN KEY REFERENCES Module(ModuleID) NOT NULL,
MessageID INT FOREIGN KEY REFERENCES Message(Message) NOT NULL
)
and was already able to insert the values for the tables Module and Message.
Now i struggle with inserting the existing connections (e.g. ModuleID = 1 with MessageID = 5,1,7,9,6) to the table Bind.
I would like to achieve this with a sql script.
Thank you in advance.
Mady

you can use this query :
INSERT INTO Module (Name) VALUES ('Name 1');
SET #ModuleID = LAST_INSERT_ID();
INSERT INTO Message (Name,Size) VALUES ('Message 1',50);
SET #MessageID = LAST_INSERT_ID();
INSERT INTO Bind (MessageID,ModuleID) VALUES(#ModuleID, #MessageID);

Related

SQL INSERT INTO with empty foreign table

I have a table with 3 values and a foreign table.
Tbl_Person
ID int PRIMARY KEY IDENTITY(1,1)
CarID int REFERENCES Tbl_Car(ID)
Name nvarchar(20)
Tbl_Car
ID int PRIMARY KEY IDENTITY(1,1)
Color nvarchar(30)
I now want to create a new Person with a new Car without caring about the Car table, sort of like this:
INSERT INTO Tbl_Person (Car, Name)
VALUES ('dont know what goes here', 'Timmy')
I'm not sure what to put inside the Car column since I just want it to exist but not care about its values just yet.
I'm sure its quite easy to find online but I have no idea how to Google for this particular problem.
You could alter the logical model to denormalize 'CarID' (remove it from 'Persons' table) and create a new table to store persons' cars called 'Person_Cars'. This avoids inserting NULL values into the model when the car is unknown. Depending on which table constraints are applied it also could allow for persons to have more than 1 car. Also, prefixing tables with 'tbl_' is not necessary. Also, both Persons and Cars seem likely to benefit from a unique constraint on the NVARCHAR column(s).
Persons
ID int not null PRIMARY KEY IDENTITY(1,1)
Name nvarchar(20) unique not null
Cars
ID int not null PRIMARY KEY IDENTITY(1,1)
Car nvarchar(30) unique not null
Person_Cars
ID int not null PRIMARY KEY IDENTITY(1,1)
PersonID int not null REFERENCES Persons(ID)
CarID int not null REFERENCES Cars(ID)
You can use NULL:
CREATE TABLE Tbl_Car (
ID int PRIMARY KEY IDENTITY(1,1),
Color nvarchar(30));
CREATE TABLE Tbl_Person (
ID int PRIMARY KEY IDENTITY(1,1),
CarID int REFERENCES Tbl_Car(ID),
Name nvarchar(20));
INSERT INTO Tbl_Person (CarID, Name) VALUES (NULL, 'Timmy');
DBFIDDLE
You have to do a logical operation. You can not just give the car an ID but it must have a name.
change Tbl_Car to :
CREATE TABLE Tbl_Car (
ID int PRIMARY KEY IDENTITY(1,1),
CarName nvarchar(30),
Color nvarchar(30));
To enter the Tbl_Person table, you must know the name of the person's car :
INSERT INTO Tbl_Person VALUES(CarID,Name)
SELECT ID,'Timmy'
FROM Tbl_Car
WHERE CarName = 'BMW'

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 :-

copy a column with identical function to another table

I want to copy a column generated by identity function, identity(1,1), to another table. However, after the process, the whole new column only shows 1.
Is there a way to fix that? thank you
CREATE TABLE Dim_Route(RtID INT Identity(1,1) Primary Key, Itinerary varchar(50) NOT NULL, )
CREATE TABLE Dim_FlightSchedule(FSID INT Identity(1,1) Primary Key, RTID INT, Constraint fk_Route Foreign KEY (RTID) REFERENCES Dim_Route(RtID), )
insert Dim_Route (Itinerary)
values
('B'),
('C'),
('D'),
('E'),
('F')
insert Dim_FlightSchedule (RTID)
select RTID from Dim_Route
Here is my code:
The original table:CREATE TABLE Dim_Route(RtID INT Identity(1,1) Primary Key,
Itinerary varchar(50) NOT NULL,
)
The destination table:CREATE TABLE Dim_FlightSchedule(FSID INT Identity(1,1) Primary Key,
RTID INT,
Constraint fk_Route Foreign KEY (RTID) REFERENCES
Dim_Route(RtID),
)
UPDATE Dim_FlightSchedule
SET Dim_FlightSchedule.RTID = Dim_Route.RTID
FROM Dim_Route
The RTID in destination table are all 1.
I don't know where I got wrong. Thank you

Why isn't my Auto Increment working in SQL Server 2008?

This is my table creation:
create table Movie
(
MovieID int NOT NULL IDENTITY (1,1) PRIMARY KEY,
MovieName varchar(40) NOT NULL UNIQUE,
CurrentStock int NOT NULL,
GenreID int NOT NULL,
RatingID int NOT NULL,
Max_Inventory int NOT NULL,
Platforms char(5) NOT NULL,
Discontinued bit,
DiscontinuedDate Date
);
create table Inventory
(
InventoryID int NOT NULL IDENTITY (1,1) PRIMARY KEY,
MovieID int Not NULL,
CurrentStock int NOT NULL,
Max_Inventory int NOT NULL
);
Stored procedures:
ALTER PROCEDURE [dbo].[InsInventory]
(#CurrentStock int,
#ChangeStock int)
as
begin
insert into Inventory(Max_Inventory, CurrentStock)
Values (#ChangeStock, #CurrentStock)
select SCOPE_IDENTITY();
END
ALTER PROCEDURE [dbo].[InsMovie]
(#GenreID int,
#RatingID int,
#Platform varchar(5),
#MovieName varchar(40)
)
AS
BEGIN
Insert into Movie (RatingID, MovieName, Platforms, GenreID)
Values (#RatingID, #MovieName, #Platform, #GenreID)
select SCOPE_IDENTITY();
SET NOCOUNT ON;
END
Foreign key:
ALTER Table Inventory
ADD CONSTRAINT fk_Inventory_Movie
FOREIGN KEY (MovieID) REFERENCES Movie(MovieID)
ALTER TABLE Movie
ADD CONSTRAINT fk_Movie_RatingLookUp
FOREIGN KEY (RatingID) REFERENCES RatingLookUp(RatingID)
ALTER TABLE Movie
ADD CONSTRAINT fk_Movie_GenreLookUp
FOREIGN KEY (GenreID) REFERENCES GenreLookUp (GenreID)
When I run my code I keep getting the error in Visual Studio
MovieID cannot be null
but it should be when I insert a row. I also made sure to manually check to see if SQL Server had the IsIdentity set, which it is. So please help a confused programmer out.
You shouldn't insert NULL as a primary key to make it generate a value, you should just don't insert that value at all by not listing it among the fields to insert. As a sample;
INSERT INTO Movie (moviename, currentstock, genreid, ratingid, max_inventory, platforms)
VALUES ('name1', 1, 1, 1, 1, '1');
A simple working sample with your exact table creation.
Below statement is your problem. your table def shows MovieID not null. but in below statement you didn't provide that.
insert into Inventory(Max_Inventory, CurrentStock)
Values (#ChangeStock, #CurrentStock)
here is what you need to do.. first you need to retrieve Movie id which will be return from executing InsMovie sproc. than you need to use that Movie Id as a prameter to InsInvetory sproc call.
according to your table def movie id is required. also for Movie table you missed two column values that i have added which are required as well.
Please see blow updated stored procedures.
ALTER PROCEDURE [dbo].[InsInventory]
(
#CurrentStock int,
#ChangeStock int,
#MovieID int
)
as
begin
insert into Inventory(MovieID, Max_Inventory,CurrentStock)
Values (#MovieID, #ChangeStock, #CurrentStock)
select SCOPE_IDENTITY();
END
ALTER PROCEDURE [dbo].[InsMovie]
(
#GenreID int,
#RatingID int,
#Platform varchar(5),
#MovieName varchar(40),
#CurrentStock int,
#max_inventory int
)
AS
BEGIN
Insert into Movie (CurrentStock, max_inventory, RatingID, MovieName, Platforms,GenreID)
Values(#CurrentStock, #max_inventory, #RatingID,#MovieName, #Platform, #GenreID)
select SCOPE_IDENTITY();
SET NOCOUNT ON;
END

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)