SQL create table using code and populate with code - sql-server

I'm working on an assignment and have created my code on NotePad++ to then copy over to SSMS, however when I create a table it brings me to the default view which is manually entering the column names and data. I want to just paste my created code into the database to create the table. How do I go about this?
Also my prof has provided data to populate my tables but I can't seem to figure out where I paste his INSERT INTO data into?
Also, for some reason I attempted to create a new query in the database i created for the assignment and pasted the code into that, but the tables don't show up even if I execute them in the Tables drop down.
Code for notepad++
CREATE TABLE tblMajors
(
MajorCode varchar(10) PRIMARY KEY NOT NULL,
MajorDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblInstructors
(
InstructorNumber int PRIMARY KEY NOT NULL,
InstructorFirst varchar(50) NOT NULL,
InstructorLast varchar(50) NOT NULL,
ContractStatus varchar(10) NOT NULL,
PhoneNumber bigint NOT NULL,
)
CREATE TABLE tblStudents
(
StudentNumber int PRIMARY KEY NOT NULL,
StudentFirst varchar(20) NOT NULL,
StudentLast varchar(20) NOT NULL,
MajorCode varchar(10) FOREIGN KEY REFERENCES tblMajors (MajorCode),
)
CREATE TABLE tblCourses
(
CourseCode varchar(10) PRIMARY KEY NOT NULL,
CourseDescription varchar(MAX) NOT NULL,
)
CREATE TABLE tblGrades
(
StudentNumber bigint FOREIGN KEY REFERENCES tblStudents (StudentNumber),
CourseCode varchar(10) FOREIGN KEY REFERENCES tblCourses (CourseCode),
Grade int NOT NULL,
IntructorNumber int FOREIGN KEY REFERENCES tblInstructors (IntructorNumber),
PRIMARY KEY (StudentNumber, CourseCode)
)

Related

SQL Server : foreign key references invalid table

I'm not sure what I'm doing wrong, but I'm getting a foreign key references invalid table message telling me that dbo.ValueStream is an invalid table.
Edit: I originally posted my code in the incorrect order. Fixed in the edit to reflect the order it was done in SSMS
CREATE TABLE dbo.ValueStream
(
ValueStreamKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_ValueStream_ValueStreamKey PRIMARY KEY,
ValueStream nvarchar(20),
)
CREATE TABLE dbo.NonConformance
(
NonConformanceKey int IDENTITY(1,1) NOT NULL
CONSTRAINT PK_NonConformance_NonConformanceKey PRIMARY KEY,
CustomerVendorKey int NOT NULL
CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey),
ValueStreamKey int NOT NULL
CONSTRAINT FK_NonConformance_ValueStream_Key_ValueStream_ValueStreamKey
FOREIGN KEY REFERENCES dbo.ValueStream(ValueStreamKey),
RepairOrder nvarchar(50) NOT NULL,
WorkOrder nvarchar(8) NOT NULL,
PartNumber nvarchar(50) NOT NULL,
SerialNumber nvarchar(50) NOT NULL,
PartDescription nvarchar(50) NOT NULL,
InductionDate datetime NOT NULL,
TriageStartDate datetime NOT NULL,
TriageCompletionDate datetime NOT NULL,
RequiresRRCA Bit NOT NULL,
NonConformanceSummary nvarchar(max) NOT NULL
);
taking out the CONSTRAINT FK_NonConformance_CustomerVendorKey_CustomerVendor_CustomerVendorKey
FOREIGN KEY REFERENCES dbo.CustomerVendor(CustomerVendorKey)
(we don't have that one)
and running the scripts seperately - first the first table and then the creation of the referencing table - this works for me.
No code errors.
You are creating dbo.NonConformance first in the script that you have posted. You need to move the CREATE TABLE dbo.ValueStream statement so that it is created first, ensuring there is a GO statement still between the two CREATE TABLE statements.
As it stands you are trying to create a foreign key to a table that does not exist.

Can't create the tables because the primary keys used as foreign keys in another table

Create Table Customer
(
Cus_id Varchar2(10) NOT NULL Primary Key,
Cus_FirstName Varchar2(20) NOT NULL,
Cus_LastName Varchar2 (20) NOT NULL,
Cus_Address Varchar2(25) NOT NULL,
Cus_City_State_Zip Varchar2(30) NOT NULL
);
Create Table Order_
(
Order_id Varchar2(10) NOT NULL Primary Key,
Order_Date Varchar2(12) NOT NULL,
Order_Status Varchar(12) NOT NULL
);
Create Table Item
(
Item_id Varchar2(10) NOT NULL Primary Key,
Item_Name Varchar2(20) NOT NULL,
Item_Price Varchar2(10) NOT NULL
);
Create Table CustomerOrderItem
(
Quantity Varchar2(8) NOT NULL,
Cus_id Varchar(10) NOT NULL Primary Key,
Order_id Varchar(10) NOT NULL Primary Key,
Item_id Varchar(10) NOT NULL Primary Key,
Foreign Key(Cus_id) References Customer(Cus_id),
Foreign Key(Oreder_id) References Order_(Order_id),
Foreign Key(Item_id) References Item(Item_id)
);
This code is a customer table with repeated orders and multiple items for one order. When I try to insert values into the table and create them. I created the fourth table due to their dependency and put three primary keys there as primary keys and foreign keys. It does not let me create the tables saying because the primary keys used as foreign keys in another table, therefore I need to drop them first to create the tables.
Your data schema neither matches what you describe, nor is a correct syntax for SQL Server. Putting aside the bad design, this is what you are trying to do:
Create Table Customer ( Cus_id Varchar(10) NOT NULL Primary Key,
Cus_FirstName Varchar(20) NOT NULL,
Cus_LastName Varchar (20) NOT NULL,
Cus_Address Varchar(25) NOT NULL,
Cus_City_State_Zip Varchar(30) NOT NULL );
Create Table Order_ ( Order_id Varchar(10) NOT NULL Primary Key,
Order_Date Varchar(12) NOT NULL,
Order_Status Varchar(12) NOT NULL );
Create Table Item ( Item_id Varchar(10) NOT NULL Primary Key,
Item_Name Varchar(20) NOT NULL,
Item_Price Varchar(10) NOT NULL );
Create Table CustomerOrderItem ( Quantity Varchar(8) NOT NULL,
Cus_id Varchar(10) NOT NULL,
Order_id Varchar(10) NOT NULL,
Item_id Varchar(10) NOT NULL,
constraint PK_CustomerOrderItem primary key (cus_id, order_id, item_id),
constraint FK_COI_Customer Foreign Key(Cus_id) References Customer(Cus_id),
constraint FK_COI_Order Foreign Key(Order_id) References Order_(Order_id),
constraint FK_COI_Item Foreign Key(Item_id) References Item(Item_id) );
Check Northwind sample database for a better sample, and for even a better one check AdventureWorks sample database as starters.
the Error message you got ORA-02449 is due to trying to drop a table that is already referenced as primary key in CustomerOrderItem table ,to solve this issue drop the CustomerOrderItem table first then drop the other tables afterwards.
Good luck.

SQL Server & Visual Studio - Insert Data in tables doesn't work

I want to insert my tables from my SQL Server Management Studio code with data via Visual Studio.
But it doesn't work. The ID of my table doesn't get a value automatically (but I have command it with identity(1,1)) and an error appears that it stands in conflict with a foreign-key-constraint.
create table [ProduktZahlungFENutzer]
(
ID int PRIMARY KEY IDENTITY(1,1) NOT NULL,
Endpreis decimal(3, 2)
);
CREATE TABLE [FHAngehörige]
(
FHAngehörigeID INT NOT NULL IDENTITY(1,1)
PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE [FENutzer]
(
FENutzerID INT IDENTITY(1,1) NOT NULL
PRIMARY KEY constraint t_nutzer
references ProduktZahlungFENutzer(ID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Please help
You have established a reference
FHAngehörigeID INT NOT NULL IDENTITY(1,1) PRIMARY KEY Constraint fhA_feN
REFERENCES FENutzer(FENutzerID),
This means that you need a record in your table FENutzer.FENutzerID that match FHAngehörigeID, in this case you cannot use IDENTITY
Your construction makes no sense - this way, you're creating two tables that depend on each other, at the primary key level - so you would have to have an existing entry in FENutzer in order to insert a new row into FHAngehörige, and this at the same time is only possible if you already have an existing row in FHAngehörige to insert the row in FEnutzer.....
You need to clean this up:
both tables need a primary key and the int identity(1,1) is a very good choice
one of the tables must reference the other, but with a normal foreign key attribute - not on the primary key.....
Since you've not given any indication as to which of the tables is the "main" table and which the "child/auxiliary" table, I'm just picking one over the other - so your table structure should be something like:
CREATE TABLE dbo.FHAngehoerige
(
FHAngehoerigeID INT NOT NULL IDENTITY(1,1)
CONSTRAINT PK_FHAngehoerige PRIMARY KEY CLUSTERED,
Name VARCHAR(50) NOT NULL,
Fachbereich INT NOT NULL,
Email VARCHAR(50) NOT NULL UNIQUE
)
CREATE TABLE dbo.FENutzer
(
-- define the PK for the table
FENutzerID INT IDENTITY(1,1) NOT NULL
CONSTRAINT PK_FENutzer PRIMARY KEY CLUSTERED,
-- define the **foreign key** to the main table
FHAngehoerigeID INT NOT NULL
CONSTRAINT FK_FENutzer_FHAngehoerige
FOREIGN KEY REFERENCES dbo.FHAngehoerige(FHAngehoerigeID),
Aktiv INT NOT NULL,
LetzterLogin datetime NOT NULL DEFAULT GETDATE(),
BENutzerID int NOT NULL
constraint FENutzer_BENutzer
foreign key references BENutzer(BENutzerID),
auth_id int not null
constraint FENutzer_auth
foreign key references auth2(id)
)
Also: I would strongly recommend (from my own personal, bad experience) to AVOID any special characters like umlauts or accents or anything like that in table and column names.....

How can I move data from one column of a parent into a new child table?

I have two tables: WordForm and WordDefinition:
CREATE TABLE [dbo].[WordForm] (
[WordFormId] VARCHAR (20) NOT NULL,
[WordId] VARCHAR (20) NOT NULL,
[Primary] BIT DEFAULT ((0)) NOT NULL,
[PosId] INT NOT NULL,
-- I want to move text data from this column into
-- the WordDefinition table column called Definition
-- and then I will remove the column from here later.
[Definition] VARCHAR (MAX) NULL,
[Sample] VARCHAR (MAX) NULL,
[Synonym] VARCHAR (100) NULL,
PRIMARY KEY CLUSTERED ([WordFormId] ASC),
CONSTRAINT [FK_WordFormPos] FOREIGN KEY ([PosId]) REFERENCES [dbo].[Pos] ([PosId]),
CONSTRAINT [FK_WordFormWord] FOREIGN KEY ([WordId]) REFERENCES [dbo].[Word] ([WordId])
);
CREATE TABLE [dbo].[WordDefinition]
(
[WordDefinitionId] INT IDENTITY (1, 1) NOT NULL,
[WordFormId] VARCHAR (20) NOT NULL,
[Definition] VARCHAR (MAX) NOT NULL
CONSTRAINT [PK_WordDefinition] PRIMARY KEY CLUSTERED ([WordDefinitionId] ASC),
)
Initially the WordForm table was created to hold single definitions but now I realize there can be more definitions for each WordForm.
To implement this I added the WordDefinition table. One WordForm row to Many WordDefinition rows.
But now what I need to do is to go through the WordForm table and add an entry with the original definition (from WordForm) and copy this into the WordDefinition table for each row in WordForm.
Is this something I could do only with SQL or would I need to use a cursor. Any help and advice on how to do this would be much appreciated.
I think you can just use 1 query INSERT INTO SELECT to do this, something like this:
INSERT INTO [dbo].[WordDefinition]
SELECT [WordFormId], [Definition]
FROM [dbo].[WordForm]
After that you can delete the old column Definition from WordForm.

Create a many to many relation and give each relation an object

I am writing a query to create a database in SQL server 2008 R2. I plan to use it with entity framework in a mvc3 application
I have users, games and highscores.
What I want ot do is this:
I want to create a many-to-many relationship between users and games.
Each User can have multiple games and each game can have multiple users.
and each relation user-game has 1 high score.
So far I created the users, games, highscores tables:
CREATE TABLE Users
(
UserId INT IDENTITY(1,1),
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(200) NOT NULL,
CreatedDate DateTime NULL,
PhoneNumber VARCHAR(32) NULL,
Password VARCHAR(64),
CONSTRAINT pk_users_userid PRIMARY KEY(UserId)
)
CREATE TABLE Games
(
GameId INT IDENTITY(1,1),
Url VARCHAR(64) NOT NULL,
CONSTRAINT pk_gamess_gameid PRIMARY KEY(GameId)
)
CREATE TABLE Highscores
(
HighscoreId INT IDENTITY(1,1),
Value INT NOT NULL,
CONSTRAINT pk_surveyors_surveyorid PRIMARY KEY(HighscoreId)
)
What is the best way to create the many-to-many user-game relation and give each relation one high score? should I create a 4th table to hold the relation? And if I do so will I be able to use the database with Entity framework in an MVC3 application or would that complicate it?
Thank you
Additional note: I am planning to use this database with entity framework in a MVC 3 web application.
CREATE TABLE Users (
UserId INT IDENTITY(1,1),
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(200) NOT NULL,
CreatedDate DateTime NULL,
PhoneNumber VARCHAR(32) NULL,
Password VARCHAR(64),
CONSTRAINT pk_users_userid PRIMARY KEY(UserId)
)
CREATE TABLE Games (
GameId INT IDENTITY(1,1),
Url VARCHAR(64) NOT NULL,
CONSTRAINT pk_gamess_gameid PRIMARY KEY(GameId)
)
CREATE TABLE Highscores (
HighscoreId INT IDENTITY(1,1),
UserID Int,
GameID Int,
Value INT NOT NULL,
CONSTRAINT pk_surveyors_surveyorid PRIMARY KEY(HighscoreId)
)
ALTER TABLE [dbo].[Highscores] ADD CONSTRAINT [FK_Highscores_Games] FOREIGN KEY([GameID])
ALTER TABLE [dbo].[Highscores] ADD CONSTRAINT [FK_Highscores_Users] FOREIGN KEY([UserID])

Resources