How to change data type of columns without dropping it - sql

CREATE TABLE DEPARTMENT(
DEPARTMENT_NAME VARCHAR(25) NOT NULL PRIMARY KEY ,
BUDGET_CODE INT NOT NULL,
OFFICE_NUM INT NOT NULL,
PHONE NUMERIC NOT NULL ,
);
I have this table that I am creating but i want to change budget code and office number in varchar instead of int. Is there a way to do this. this table is linked to other tables with foreign key. So i can't drop it and create a new one.

Try this
ALTER TABLE dbo.DEPARTMENT
ALTER COLUMN BUDGET_CODE VARCHAR(100)
ALTER COLUMN OFFICE_NUM VARCHAR(100)

Related

The INSERT statement conflicted with the FOREIGN KEY constraint"

I'm trying to insert data into my SQL Server 2014 build and I keep getting this error. I tried searching all over the internet and at my whits end, I sort of get what people were saying but still having difficulty understanding what's wrong with my particular code.
All tables are empty without data. I cannot add data once the foreign keys are set. I read that both tables must be populated for this to work but how does that happen when I can't add anything? If I add data before the foreign key, then I'm unable to add foreign keys. Please help!
When trying to insert data into Gym row using the INSERT INTO I get this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Gym__staffNo". The conflict occurred in database "FitnessApp", table "dbo.Staff", column 'staffNo'.
This also happens when trying to add data into the Equipment or Staff tables as well.
See code here:
Schema:
CREATE TABLE Gym
(
gymNo int NOT NULL IDENTITY(1,1),
staffNo int NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Staff
(
staffNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
position varchar(50) NOT NULL,
firstName varchar(50) NOT NULL,
lastName varchar(50) NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL,
hireDate date NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Member
(
memberNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
firstName varchar(30) NOT NULL,
lastName varchar(30) NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL,
memberSince date NOT NULL,
scheduleID int NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Schedule
(
scheduleID int NOT NULL IDENTITY(1,1),
staffNo int NOT NULL,
trainDate date NOT NULL,
trainTime time(0) NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Equipment
(
equipNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
staffNo int NOT NULL,
name varchar(50) NOT NULL,
quantity int NOT NULL
) ON [fitnessPlusGroup1];
Foreign key relationships setup:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Member
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Member
ADD FOREIGN KEY (scheduleID) REFERENCES Schedule(scheduleID);
ALTER TABLE Schedule
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Equipment
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Equipment
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
The insert commands that give errors:
INSERT INTO Gym(staffNo, streetAddress, streetAddress2, city, state, zip, phone)
VALUES (1, '7300 W Greens Rd', NULL, 'Houston', 'TX', '77064', '2818946151');
Any help would be much appreciated sorry if this seems like a bit much and I hope I provided all the info I could..
I think the problem is in your table design. Take these two FKEY, as an exmpale:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
You cannot add a record to Gym until you've added the supporting staffNo to Staff. But you cannot add a record to Staff until you've added the supporting gymNo to Gym. These keys prevent you populating either table, as both require records to be present in the other.
Why is this? Because an FKey is like a promise. It guarantees that the value in column x can always be found in table y. In order to fulfill this promise table y must be populated first. But when you have a circular reference, back to the original table, this can never be achieved.
Here is one possible solution. You could remove the staffNo from Gym and GymNo from Staff. Then add a new table StaffGym. This table would have two fields staffNo and gymNo. It would be populated after Staff and Gym, providing a bridge between the two. This is called a cross reference table, or sometimes xref for short.
You say:
All tables are empty without data.
So there is no staffNo with id = 1 in your Staff. You've got a foreign key constraint so you can only reference items that exist. So you first need to populate the lookup data in Staff before you can link to it with an ID.
Also, remove one of the constraint between Staff and Gym, you have this:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo)
REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo)
REFERENCES Gym(gymNo);
When you only need one of these. I'd say remove it from Gym, as a Gym could have many staff I'd assume, and also remove the StaffNo column from Gym. As this is preventing you from creating one without the other. Once you've removed that link, you should insert data in the correct order.
The order of the inserts is key. If you remove the column I suggested above, you should insert in the following order based on your constraints:
Gym
Staff (requires gym record)
Schedule (requires staff record)
Member (requires schedule record)
Equipment (requires gym and staff record)

How i can change and run sql file into mssql

I have my database in sqlite .I exported sql file from sqlite manager. Now on executing that file into Microsoft SQL Server 2012 it is giving error on following lines.
DROP TABLE
IF EXISTS "Admin";
CREATE TABLE "AdvancePayments" (
"Id" INT PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
"date" VARCHAR,
"Name" VARCHAR,
"Amount" INT,
"Remarks" VARCHAR);
INSERT INTO "AdvancePayments"
VALUES (
1,
'11/22/2013',
'wqqw',
21,
'fgdsr');
CREATE TABLE "DVouchers" (
"DVid" INT PRIMARY KEY NOT NULL,
"vdate" VARCHAR DEFAULT(NULL),
"Vehiclenum" VARCHAR,
"Coupen" BOOL,
"Saleperson" VARCHAR,
"DVnumber" INT,
"Ares" VARCHAR,
"Ctitle" VARCHAR,
"remarks" VARCHAR,
"mEntry" BOOL,
"Cust_Id" INT,
FOREIGN KEY (Cust_Id) REFERENCES Customer_New(Cust_Id));
What is correct syntax for mssql?
You should write it as:
--DROP TABLE IF EXISTS Admin;
--query to drop a table
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
DROP TABLE [dbo].[TableName]
GO
CREATE TABLE [AdvancePayments]
(
[Id] INT IDENTITY(1,1) PRIMARY KEY NOT NULL ,--The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature
[date] VARCHAR(10),-- best practice is to use datetime datatype to store date feilds.
[Name] VARCHAR(100),
[Amount] INT,
[Remarks] VARCHAR(1000)
);
INSERT INTO AdvancePayments
VALUES (
--1,-- you cannot give an explicit value to identity column untill IDENTITY_INSERT is ON. So comment this.
'11/22/2013',
'wqqw',
21,
'fgdsr');
CREATE TABLE [DVouchers] (
[DVid] INT PRIMARY KEY NOT NULL,
[vdate] VARCHAR(20) DEFAULT(NULL),
[Vehiclenum] VARCHAR(100),
[Coupen] BIT,-- Bit is the datatype used for Boolean values.
[Saleperson] VARCHAR(100),
[DVnumber] INT,
[Ares] VARCHAR(100),
[Ctitle] VARCHAR(100),
[remarks] VARCHAR(100),
[mEntry] BIT,
[Cust_Id] INT,
FOREIGN KEY (Cust_Id) REFERENCES Customer_New(Cust_Id)
);
Note: In MS SQL default length of varchar datatype is 1. so you will have to specify length to each
varchar variable.
TSQL:
IF NOT OBJECT_ID('dbo.TableToDrop') IS NULL
BEGIN
DROP TABLE dbo.TableToDrop
END;
// change dbo. to your schema if necessary

When I create a table in SQL, how do I set an attribute not null?

I wanna create a table in SQL, and if the I wanna set the attributes to NULL, how do I do it?
For example, I wanna create a table named Courses and its attributes "CourseNo" and "Title" must not be null. I created one below:
CREATE TABLE Courses(
CourseNo INTEGER CHECK(100<=CourseNo<=999) PRIMARY KEY,
Title VARCHAR(100),
)
ALTER TABLE Courses
ALTER COLUMN CourseNo INTEGER NOT NULL
ALTER COLUMN Title VARCHAR(100) NOT NULL
Is this correct?
whatever you wrote that one correct but good practice is to write not null at a time of defining table. do like this:
CREATE TABLE Courses(
CourseNo INTEGER CHECK(100<=CourseNo<=999) PRIMARY KEY,
Title VARCHAR(100) NOT NULL,
)
primary key is by default NOT NULL always, hence you no need to declare it as NOT NULL
NOT NULL in alter is used when u want to make change in column definations of table later
Change that Title VARCHAR(100) to Title VARCHAR(100) NOT NULL.

SQL Server : create error how to write database name with the table name

CREATE DATABASE agom COLLATE Arabic_CI_AS
CREATE TABLE Branches
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Brands
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
NAME VARCHAR(255) NOT NULL
)
CREATE TABLE agom.Work_Order
(
NUMBER INT NOT NULL,
BRANCHID INT NOT NULL,
BRANDID INT NOT NULL,
WDATE DATE NOT NULL,
REPAIRSTATUS VARCHAR(255),
REPAIRCOST VARCHAR(255),
REMARK VARCHAR(500),
PRIMARY KEY (NUMBER,BRANCHID,BRANDID)
)
CREATE TABLE agom.Profiles
(
ID INT PRIMARY KEY NOT NULL IDENTITY,
USERNAME VARCHAR(25) NOT NULL,
PASS VARCHAR(25) NOT NULL
)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT branchfk
FOREIGN KEY (BRANCHID) REFERENCES Branches(ID)
ALTER TABLE agom.Work_Order
ADD CONSTRAINT brandfk
FOREIGN KEY (BRANDID) REFERENCES Brands(ID)
I get an error that cannot create table
I try to write database name with the table name db.tablename but it's not working
I need to create the database then create the tables and its constraints but I don't know where is the error.I am a sql noob
It's never Database.Table.
It's either Table, or Schema.Table, or Database.Schema.Table, or Server.Database.Schema.Table.
You probably just want to insert USE agom right after create database, and then only refer to tables by name.
Alternatively, you can refer to your tables as agom.dbo.Work_Order, dbo being the default database schema.
See Using Identifiers As Object Names for general reference.

SQL Server add primary key

I have a table that needs to be given a new primary key, as my predecesor used a varchar(8) row as the primary key, and we are having problems with it now. I know how to add the primary key, but am not sure of the correct way to add this new primary key to other tables that have the foreign key. Here is what I have:
users table:
old_user_id varchar(8)
...
...
new_user_id int
orders table:
order_id int
...
...
old_user_fk varchar(8)
new_user_fk int(11)
I need to get the same results whether I join the tables on users.old_user_id=orders.old_user_fk or users.new_user_id=orders.new_user_fk. Any help is appreciated.
What is int(11)? SQL Server only has tinyint, smallint, int and bigint
I would suggest you add the new columns to all the tables then update the values so that they match....run a couple of queries to make sure it all works. drop the PK and FK constraints and add new PK and FK constraints using the new columns
of course I would back up all these tables just in case
select * into backup_ orders from orders
This way you always have that data in case you need to roll back
Replace your varchar with int, do not keep duplicates in the same table.
Write some TSQL similar this code I used recently:
BEGIN TRANSACTION
-- temp tables to hold data
DECLARE #HeaderTemp table
(vid varchar(8),
[Name] varchar (50) )
DECLARE #SecondaryTemp table
(vid_fk varchar(8),
[Value] varchar (50) )
-- store table data
INSERT INTO #HeaderTemp
SELECT * FROM [Header]
INSERT INTO #SecondaryTemp
SELECT * FROM [Secondary]
-- empty data from tables
DELETE FROM [Secondary]
DELETE FROM [Header]
-- drop constraints
ALTER TABLE [SECONDARY] DROP CONSTRAINT [FK_SECONDARY_HEADER]
ALTER TABLE [dbo].[HEADER] DROP CONSTRAINT [PK_HEADER]
-- convert varchar to int
ALTER TABLE [SECONDARY] ALTER COLUMN VID_FK INT NOT NULL
ALTER TABLE [HEADER] ALTER COLUMN VID INT NOT NULL
-- re-create constraints
ALTER TABLE [dbo].[HEADER] ADD CONSTRAINT [PK_HEADER] PRIMARY KEY CLUSTERED
(
[vid] ASC
)
ALTER TABLE [dbo].[SECONDARY] WITH CHECK ADD CONSTRAINT [FK_SECONDARY_HEADER]
FOREIGN KEY([vid_fk]) REFERENCES [dbo].[HEADER] ([vid])
-- put data back
INSERT INTO [Header]
SELECT * FROM #HeaderTemp
INSERT INTO [Secondary]
SELECT * FROM #SecondaryTemp
COMMIT TRANSACTION