SQL Query not working due to Foreign Key - asp.net

I have two tables for a hospital system
patient
(PK) ID - int (auto increments)
Name -varchar
surname -varchar
DOB - varchar
Email- varchar
Phone -varchar
(FK)address_ID
and
address table
Address(ID)-int (auto increment)
Line1 - varchar
Line2 - varchar
city - varchar
state - varchar
everytime I try and register a new patient, it doesn't include Address ID in the patient table. I have it address table and address_id linked to the patient table for address_ID in the database diagram as its foreign key, it keeps giving me an error saying its null. So if it doesn't automatically go in the patient table how do I auto increment it so that it stays the same as the address_ID in the address table?
This is the code I'm using to insert the values from the form.
string query1 = "insert into patient(name,surname,dob,email,phone) values (#pname, #psurname, #pdob, #pemail, #pphone)";
string query2 = "insert into patient_address(Line1,Line2,city,state) values (#pline1, #pline2, #pcity, #pstate)";
SqlCommand cmd1 = new SqlCommand(query1, con);
cmd1.Parameters.AddWithValue("#pname", pname.Text);
cmd1.Parameters.AddWithValue("#psurname", psurname.Text);
cmd1.Parameters.AddWithValue("#pdob", dob.SelectedValue);
cmd1.Parameters.AddWithValue("#pemail", pemail.Text);
cmd1.Parameters.AddWithValue("#pphone", pphone.Text);
SqlCommand cmd2 = new SqlCommand(query2, con);
cmd2.Parameters.AddWithValue("#pline1", pline1.Text);
cmd2.Parameters.AddWithValue("#pline2", pline2.Text);
cmd2.Parameters.AddWithValue("#pcity", pcity.Text);
cmd2.Parameters.AddWithValue("#cstate", pstate.SelectedValue);
con.Open();
cmd2.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
con.Close();
If anyone could offer some kind of guidance it would be helpful! Thanks.

The address_ID is a (FK) can be Null or Not Null (you may check if it's allow to accept null or not (null-able or not), so check if (FK) accept to be null or not
In the 1:N relation:
If the (FK) is accept to be null some times, that mean some of patients here do not have an address (so it's not required).
But if the (FK) is not accept to be null, so all the patients should have an address, and it should not be null.
And the (PK) should not be null at all.
So in your case I think the simplest way to add a custom constraints
or add one extra column (IsAdressExist) to the patient table,
or simply first add an addition row in the address_table which will refer to (empty address with Address(ID)=-1 for example), then set the default value for the patients that do not have an address with (FK)address_ID =-1
or just set the Address(ID_FK) Default Value or Binding as a (NULL)
If you want to add a new address to the address table and you need to use the same new address to be FK to the patient table, so you need to (the simplest way):
1- Add the new address to the address table.
2- Get the MAX Address_ID (PK) from the address table
3- Use that max address_ID and insert it to the patient table as FK.
OR
You need to create one long query that will do the same previous steps that I mentioned above.

Related

MariaDB Check value of an attribute w/ another table attribute

I want to assure at inserting a manager that department manager start date [DEPARTMENT.mgr_start_date] is coming after his birthdate [EMPLOYEE.bdate],
how can I do that?
CREATE TABLE IF NOT EXISTS EMPLOYEE
(
ssn INT(16) unsigned NOT NULL,
fname VARCHAR(16),
lname VARCHAR(16),
bdate DATE,
address VARCHAR(32),
gender enum('m','f'),
salary decimal(16,2),
Dno VARCHAR(8),
PRIMARY KEY (ssn)
);
CREATE TABLE IF NOT EXISTS DEPARTMENT
(
mgr_ssn INT(16) unsigned,
Dname VARCHAR(32),
mgr_start_date DATE,
Dnumber VARCHAR(8),
PRIMARY KEY (Dnumber),
FOREIGN KEY (mgr_ssn) REFERENCES EMPLOYEE(ssn)
);
You would have to do this with a trigger.
CHECK constraints can reference only columns in the table where the constraint is defined.
The full SQL standard includes a type of constraint called an ASSERTION, which allows multi-table constraints, but MariaDB does not implement this feature of SQL (very few brands of SQL databases do implement it).
CREATE TRIGGER t BEFORE INSERT ON DEPARTMENT
FOR EACH ROW BEGIN
IF NEW.mgr_start_date < (SELECT bdate FROM EMPLOYEE WHERE ssn = NEW.mgr_ssn) THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'manager is way too young';
END IF;
END
Test:
insert into EMPLOYEE set ssn=123, bdate='2021-01-01';
insert into DEPARTMENT set mgr_ssn=123, dnumber='1', mgr_start_date='2010-01-01';
ERROR 1644 (45000): manager is way too young

how to store auto increment id with string in mysql database

i want to store auto increment id with string "SDMP" HOW TO DO THAT? when id increment it will be like SDMP1, SDMP2,....Like that
"Insert concat('SDMP', m_id) as id from merchant where m_id='" + id + "'";
I WANT TO SHOW DRIVER ID LIKE SDMP1 IN GRIDVIEW BUT I WANT ID IN SDMP1 FORMAT
If you want to update the existing table (where m_id is int and auto increment) then you can use this(before update query you need to change datatype of m_id)
ALTER TABLE merchant
MODIFY COLUMN id varchar(50);
then use update query
UPDATE merchant set m_id=CONCAT("SDMP",m_id);
OR
If you want to insert m_id as SDMP1, SDMP2 autoincrement then you can use this
Get Last ID
Get the INT part within the string
Increment the value
Concatenate
Save to DB
moreinfo
INSERT INTO merchant
SELECT CONCAT("SDMP",SUBSTRING(m_id,5)+1),"abc4"
FROM merchant order by m_id desc limit 1;
NOTE: if no row in the DB then manually insert SDMP1 as the first row in DB
OR
Keep thing simple, you keep m_id as int auto_increment in DB and while retrieving data from DB concat with SDMP CONCAT("SDMP",m_id)
and while searching in DB take integer part from gridview of m_id column

Read last Inserted row in Sql according to its Time stamp

sql has a Table called emp.
emp(emp_id int IDENTITY primary key, EmployeeName varchar(50),.......)
I want to Insert a record to above table. Here is my code in asp.net.
DBconnection dbcon = new DBconnection();
string query = "insert into emp values('" + TextBox_EmpName.Text + "','" + ....);
int no1 = dbcon.insertQuery(query);
I have another table called emp-relation
emp-relation(emp_id int primary key, count int, ....)
-- foreign key (emp_id)references emp(emp_id)
My problem is when I inserting the emp row ,I dont know what is the emp_id since it created by auto. And when I am going to insert to emp-relation , I want to get emp-id since it is the foreign key.
How can I do this? Is there any way to read last Insert row in Sql according to Time stamp or some thing? I believe that records are not sorted according to inserted timestamp in nature. please help me.
There's bascally two ways. The first way is to return the new ID from the first insert query:
insert into emp values(...)
select scope_identity() as NewID
The second way is to lookup the first row when you insert into the relation table:
insert emp-relation
(emp_idm, ...)
select emp_id
, ...
from emp
where emp_name = #EmpName
You have to pass in enough columns to make the reference unique.

How to autogenerate the username with specific string?

I am using asp.net2008 and MY SQL.
I want to auto-generate the value for the field username with the format as
"SISI001", "SISI002",
etc. in SQL whenever the new record is going to inserted.
How can i do it?
What can be the SQL query ?
Thanks.
Add a column with auto increment integer data type
Then get the maximum value of that column in the table using "Max()" function and assign the value to a integer variable (let the variable be 'x').
After that
string userid = "SISI";
x=x+1;
string count = new string('0',6-x.ToString().length);
userid=userid+count+x.ToString();
Use userid as your username
Hope It Helps. Good Luck.
PLAN A>
You need to keep a table (keys) that contains the last numeric ID generated for various entities. This case the entity is "user". So the table will contain two cols viz. entity varchar(100) and lastid int.
You can then have a function written that will receive the entity name and return the incremented ID. Use this ID concatenated with the string component "SISI" to be passed to MySQL for insertion to the database.
Following is the MySQL Table tblkeys:
CREATE TABLE `tblkeys` (
`entity` varchar(100) NOT NULL,
`lastid` int(11) NOT NULL,
PRIMARY KEY (`entity`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The MySQL Function:
DELIMITER $$
CREATE FUNCTION `getkey`( ps_entity VARCHAR(100)) RETURNS INT(11)
BEGIN
DECLARE ll_lastid INT;
UPDATE tblkeys SET lastid = lastid+1 WHERE tblkeys.entity = ps_entity;
SELECT tblkeys.lastid INTO ll_lastid FROM tblkeys WHERE tblkeys.entity = ps_entity;
RETURN ll_lastid;
END$$
DELIMITER ;
The sample function call:
SELECT getkey('user')
Sample Insert command:
insert into users(username, password) values ('SISI'+getkey('user'), '$password')
Plan B>
This way the ID will be a bit larger but will not require any extra table. Use the following SQL to get a new unique ID:
SELECT ROUND(NOW() + 0)
You can pass it as part of the insert command and concatenate it with the string component of "SISI".
I am not an asp.net developer but i can help you
You can do something like this...
create a sequence in your mysql database as-
CREATE SEQUENCE "Database_name"."SEQUENCE1" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 001 START WITH 21 CACHE 20 NOORDER NOCYCLE ;
and then while inserting use this query-----
insert into testing (userName) values(concat('SISI', sequence1.nextval))
may it help you in your doubt...
Try this:
CREATE TABLE Users (
IDs int NOT NULL IDENTITY (1, 1),
USERNAME AS 'SISI' + RIGHT('000000000' + CAST(IDs as varchar(10)), 4), --//getting uniqueness of IDs field
Address varchar(150)
)
(not tested)

Inserting into two tables and Identity_Scope()

I am building a forum and I have two tables:
Threads
-------
ThreadID
UsersID
Date
ThreadTitle
ThreadParagraph
ThreadClosed
Topics
-----
TopicsID
Theme
Topics
Date
The ThreadID is connected to the users table with a primary key:
Topics.TopicsID(PK)==Threads.TopicID(FK)
First i insert into the Topics table and then to the Threads table. My goal is to obtain the ID of Topics.TopicID with Identity_Scope() and pass it to the second insert which is Threads.TopicID
Here is what i have done, but i am not sure if it is correct:
StringBuilder insertCommand = new StringBuilder();
insertCommand.Append("DECLARE #TopicsID int");
insertCommand.Append("INSERT INTO Topics(Theme,Topics,Date)");
insertCommand.Append("VALUES('#topic,#subTopic,GETDATE()')");
insertCommand.Append("SET #TopicsID = SCOPE_IDENTITY()");
insertCommand.Append("INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)");
insertCommand.Append("VALUES('#uniqueIdentifier,#TopicsID,GETDATE(),#questionTitle,#questionParagraph,0')");
I have got all the otehr parameters obtained from the controls the users presses or feeds information into, so dont worry about them. All i am worried about is passing the same TopicID from the Topic table to Thread table (Column name: TopicID).
Both Magnus & Damien_The_Unbeliever are right - you have few syntax errors (or typos). Correct insert command should be something like
insertCommand.Append(#"
DECLARE #TopicSID int
INSERT INTO Topics(Theme,Topics,Date)
VALUES(#topic,#subTopic,GETDATE())
SET #TopicSID = SCOPE_IDENTITY()
INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed)
VALUES(#uniqueIdentifier,#TopicSID ,GETDATE(),#questionTitle,#questionParagraph,0)
");

Resources