Table issue in SQL Server 2008 - sql-server-2008

I have a table in SQL Server 2008 like this:
Column DataType
-----------------------
FID numeric(18, 0)
Name varchar(50)
DOB datetime
MobileNo numeric(18, 0)
EmailId varchar(50)
add1 varchar(50)
add2 varchar(50)
add3 varchar(50)
Pincode numeric(18, 0)
UpdateDate datetime
In this table FID should be changed to varchar(50) without dropping (deleting) the table..
How to do this and also FID is set as primary key to the above table and also as a foreign key to other tables

As I said - I would leave the column FID as it is - otherwise, you'll have a ripple effect throughout your entire data model, and this is really really not what you want to do.
What you can do is this: create a new, separate column that contains that new prefix that the "hgiher ups" are so desperate for, and concatenates this with the FID value - but it's a separate column, and you don't need to change any of the references at all.
ALTER TABLE dbo.YourTable
ADD FID2 AS 'MU' + CAST(FID AS VARCHAR(20)) PERSISTED
With this, you'll get a VARCHAR typed new column called FID2 which will have values like MU1, MU2 ..... and so on - automatically, no changes necessary, no messy table re-creations and data copying.... it just works!

Tools->Options->designers->(Unmark)Prevent saving changes that require table recreation

Right click table -> Design -> Change the numeric(18, 0) to varchar(50) -> Save
It will ask for confirmation since changing from one data type to another removes certain precision values.
The best practice is to keep Primary and foriegn keys unique numbers. But you may opt for unique code values too which are varchar values
And one more thing, changing the primary key field datatype automatically changes the datatype of all relational foreign key fields in other tables too.

Related

What's the best practice to design a table that would have different fields on different conditions?

I need advice in creating tables where there would be different fields based on a condition. I'm pretty new to psql, so I don't really know if I'm going the right way and would appreciate any tips / advice!
Currently I have a table to represent a meeting_note, which can either be a voice recording OR a text.
When the meeting note is of type text, it must have a meeting_content, and can have an optional meeting_summary. audio_source should be null.
When the meeting note is of type audio, it must have an audio_source and the fields meeting_content and meeting_summary should be null.
I was also thinking of creating two tables - one for type audio and another for text, but there is a unique constraint on created_at which represents a date like May 11th. I wasn't sure how to add this constraint between two tables.
Here are the fields for the table meeting_note
id serial PRIMARY KEY,
meeting_id integer REFERENCES meeting(id),
meeting_note_type enum('audio', 'text') NOT NULL,
meeting_content text,
summary varchar(255),
created_at varchar(10) NOT NULL,
recording_source varchar(255)
and the constraints:
UNIQUE (to_char(created_at, 'YYYY-MM-DD')),
CHECK (NOT (meeting_note_type = 'text' AND meeting_content IS NULL)),
CHECK (NOT (meeting_note_type = 'audio' AND audio_source IS NULL)),
CHECK (NOT (meeting_content IS NULL AND audio_source IS NULL),
CHECK (NOT (meeting_content IS NOT NULL AND audio_source IS NOT NULL),
CHECK (NOT (audio_source IS NOT NULL AND summary IS NOT NULL))
Appreciate any help on this. Thank you so much in advance!
There are two common approaches to this problem - using a table-per-type and using one table for everything. The approach you describe in the question is one table for everything; your definition is pretty accurate.
Here is how to do a table-per-type solution: make a "master" table for all notes, and then a table for each note sub-type, like this:
create table note_master(
id serial PRIMARY KEY,
meeting_id integer REFERENCES meeting(id),
created_at varchar(10) NOT NULL
)
create table note_text (
id serial REFERENCES note_master(id),
meeting_content text,
summary varchar(255),
)
create table note_audio (
id serial REFERENCES note_master(id),
recording_source varchar(255)
)
To query for everything you do left-outer joins to note_text and note_audio. This approach lets you skip the enum because you can always figure out what kind of note it is by examining the results of the join.

Is it possible to declare functional dependencies among non-primary keys in a single table?

Let's assume a functional dependency: R(A,B,C,D) & FDs{ A->B, A->C, (B,C)->D }
A can identify any tuple. Defining A as a primary key, we can implement the dependency hold between A and others. But the combination of B & C can also uniquely identify D.
CREATE TABLE `test` (
`A` INT NOT NULL ,
`B` VARCHAR(100) NOT NULL ,
`C` VARCHAR(100) NOT NULL ,
`D` VARCHAR(100) NOT NULL,
PRIMARY KEY (`A`)
);
This SQL only contains the dependency between A and others. But this SQL does not say that B,C can also uniquely identify D.
Is it possible to define the dependency between B,C and D using a single table in MySQL?
I think one way is to use another table. One table for R(A,B,C) & FDs{ A->B, A->C }. And another table for R(B,C,D) & FDs{ (B,C)->D }. However, I would like to use a single table.
If ssn is the PRIMARY KEY, then GROUP BY should be happy. Please provide the SQL that is giving you trouble, plus the SHOW CREATE TABLE.
Is this valid: name = CONCAT(fname, ' ', lname)? If so, then you should not be storing name. It is a no-no in databases to have redundant information.
You could have a virtual "generated" column instead of an actual name column.

Error Code: 1136. Column count doesn't match value count at row 1 why?

USE Airline;
CREATE TABLE Responsible_for(
Time_work TIME NOT NULL,
date_work DATE NOT NULL,
Staff_ID INT NOT NULL,
Passenger_ID VARCHAR(45) NOT NULL,
CONSTRAINT FOREIGN KEY(Passenger_ID) REFERENCES Passenger(Passenger_ID),
CONSTRAINT FOREIGN KEY(Staff_ID) REFERENCES Staff(Staff_ID));
SELECT * FROM airline.Responsible_for;
INSERT INTO Responsible_for VALUES(
('04:00:00','2019-04-01',1235,'1102546778'));
why there is error?
thank you
You have an additional pair of parentheses around the list of values that should not be there.
That should be:
INSERT INTO Responsible_for(time_work, date_work, staff_id, passenger_id)
VALUES ('04:00:00','2019-04-01',1235,'1102546778');
Notes:
it is a good practice to always enumerate the columns to insert; this prevents hard-to-debug issues, and can make the code resilient to changes in the structure of the target table
you use airline at the beginning of the script, so there is no need to prefix the table name with the schema name in the insert statement
I would recommend against storing the date and time components in separate columns; this makes things unnecessarily complicated (and less efficient) when you need to compare it against a datetime; MySQL has the datetime datatype, that is meant to store both together

Duplicate entry '0' for key 'PRIMARY'

I don't understand why I'm getting this error when trying to populate this table. There is nothing in the table at the moment so I don't understand why there would be a duplicate...
This is the code I'm using:
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
suppliers table...
CREATE TABLE suppliers(
supp_id int NOT NULL,
company_name character(15) NOT NULL,
town character(15)
phone character(15)
primary key(supp_id)
);
This occurs when you have a primary key but do not give it an initialization value. The insert itself is causing the duplication.
In your case, two possibilities come to mind:
supp_id is the primary key and declared as a number. In older versions of MySQL, I think the string values get silently converted to numbers. Because the leading characters are letters, the value is 0.
You have another id field that is the primary key, but given no value and not declared auto_increment.
EDIT:
I suspect you want the following code:
CREATE TABLE suppliers (
supplierId int NOT NULL auto_increment primary key,
supp_name varchar(255) unique,
company_name varchar(15) NOT NULL,
town varchar(15),
phone varchar(15)
);
INSERT INTO Suppliers(supp_name, company_name, town, phone)
Values ('ADT217', 'AdTec', 'Birmingham', '0121-368-1597'),
('CPS533', 'CPS', 'Maidenhead', '01382-893715'),
('FCL162', 'ForComp Ltd', 'Nottingham', '01489-133722'),
('KBC355', 'KBC Computers', 'Glasgow', '0141-321-1497');
Some notes:
Usually you want varchar() rather than char(), unless you really like lots of spaces at the end of strings.
I added a unique supplier name to the table and declared the id to be a auto_increment.
Single quotes are ANSI standard for string constants. MySQL (and some other databases) allow double quotes, but there is no reason to not use the standard.
With your table you can get the error like "Incorrect Integer Value", but depending on MySQL server configuration it can do conversion(string->int) automatically for your query string must become "0" as result of this it makes 2 rows with 0 as supp_id and get error Duplicate entry '0' for key 'PRIMARY'. I guess you are using InnoDB as table type, in this case query will run as transaction and it will rollback after first error(for this example it will be second row).
DROP TABLE suppliers; -- Will drop your old table
CREATE TABLE suppliers(
supp_id varchar(30) NULL, -- You can set length as you wish
company_name character(15) NOT NULL,
town character(15),
phone character(15),
primary key(supp_id)
);
INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");
After changing type insert will work without problems.
In Wordpress, when we clone the website, the media and user roles are not working. The error is as below:
WordPress database error Duplicate entry '0' for key 'PRIMARY' for query
INSERT INTO `wp_334_actionscheduler_logs`
(`action_id`, `message`, `log_date_gmt`, `log_date_local`)
VALUES (0, 'action complete via WP Cron', '2021-02-17 05:29:40',
'2021-02-17 05:29:40')
made by
do_action_ref_array('action_scheduler_run_queue'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_QueueRunner->run,
ActionScheduler_QueueRunner->do_batch,
ActionScheduler_Abstract_QueueRunner->process_action,
do_action('action_scheduler_after_execute'),
WP_Hook->do_action,
WP_Hook->apply_filters,
ActionScheduler_Logger->log_completed_action,
ActionScheduler_DBLogger->log

Auto Increment in sql with specific name

i need autoincrement. for start like abc_1,abc_2. like this format? below shown code is for auto increment. but i need format like abc_ is constatanct then auto increment, format like abc_1,abc_2..
CODE
sql = "CREATE TABLE MY_TABLE
(
table_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(table_id),
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
)"
You have 2 options - both include keeping the autoincrement field exactly as it is.
1st Option is to add a short char type field, which simply stores your Alpha part. When you want to retrieve the whole key, then you can SELECT (alpha_part + table_id) as ID. As you can see this generates smaller storage, but requires more work for each select statement.
2nd option is to add a longer column that gets populated by an insert trigger normally. It is simply storing the concatenation on creation and then you don't have to concatenate it when you want to select it. This option also allows you to create an index or clustered index easier.
CREATE TABLE MY_TABLE (
table_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(table_id),
alpha_part varchar(10) NOT NULL, -- This
display_id varchar(40) NOT NULL, -- OR This (not both)
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45) )
"Database Id" and "Insurance Policy Id" are two separate entities - they may contain the "same" number, but don't mix up what the database needs to perform effectively, with what your business application needs to generate IDs for customers. Business rules and database Id are separate entities. You can "seed" a policy Id from a database generated one, but if something changes the policy id (yes this happens) your database suddenly needs to be refactored and you don't want that to happen.
You could add another column to derive this value, then have a trigger that automatically updates this column to add the derived value whenever a row is inserted.
However, it is not clear why this would be needed. It is likely better to just store the number and derive the form abc_123 where that value needs to be used.
It was an interesting thing. so I googled custom auto increment structure and found some links. Most of the people are saying that its better to use trigger before insertion and I think it can be on possible solution for your problem. Look at the following link.
http://www.experts-exchange.com/Database/MySQL/Q_27602627.html