SQL query to insert IDs in tables - sql

I will try to be short and concise, I have this table which contains rows of data.
I also have 3 separate tables, Surgery, TypeOfSurgery and Procedure, each filled with additional data, and each should contain the Id (foreign key) to the previous table.
For example TypeOfSurgery has a FK column SurgeryId, Procedure has FK column TypeOfSurgeryId etc, I need to update the existing entries in these tables!
And I also have 3 dropdowns, each connected to the previous one.
EXPECTED OUTPUT:
If I choose Abdominal Surgery the following dropdown should be populated with Appendectomy and Caesarian Section, further if I choose Appendectomy the next dropdown should be populated with procedure A, and if I choose Caesarian section the next dropdown should contain procedure B and Procedure C etc...
My question is how do I give the corresponding IDs to each row in each table with one query, so the dropdowns will work as I described above.
Thanks!

It sounds like you're asking how to decompose this denormalised data into three different tables.
This is how I would do it.
(I wouldn't normally answer a question where the post doesn't contain DDL)
First ensure that all three target tables have an identity field defined against the PK so that keys are autogenerated.
Populate Surgery. SurgeryID in this table must be IDENTITY
INSERT INTO Surgery (SurgeryName)
SELECT DISTINCT Surgery FROM YourTable
Populate TypeOfSurgery. TypeOfSurgeryId must be IDENTITY
INSERT INTO TypeOfSurgery (SurgeryID, TypeOfSurgeryName)
SELECT DISTINCT S.SurgeryID, SRC.TypeOfSurgery
FROM YourTable SRC
INNER JOIN Surgery S
ON S.SurgeryName = SRC.Surgery
Populate Procedure. ProcedureId must be IDENTITY
INSERT INTO Procedure (TypeOfSurgeryId, ProcedureName)
SELECT DISTINCT S.TypeOfSurgeryId, SRC.Procedure
FROM YourTable SRC
INNER JOIN TypeOfSurgery S
ON S.TypeOfSurgeryName = SRC.TypeOfSurgery

Related

How to get the differences between two - kind of - duplicated tables (sql)

Prolog:
I have two tables in two different databases, one is an updated version of the other. For example we could imagine that one year ago I duplicated table 1 in the new db (say, table 2), and from then I started working on table 2 never updating table 1.
I would like to compare the two tables, to get the differences that have grown in this period of time (the tables has preserved the structure, so that comparison has meaning)
My way of proceeding was to create a third table, in which I would like to copy both table 1 and table 2, and then count the number of repetitions of every entry.
In my opinion, this, added to a new attribute that specifies for every entry the table where he cames from would do the job.
Problem:
Copying the two tables into the third table I get the (obvious) error to have two duplicate key values in a unique or primary key costraint.
How could I bypass the error or how could do the same job better? Any idea is appreciated
Something like this should do what you want if A and B have the same structure, otherwise just select and rename the columns you want to confront....
SELECT
*
FROM
B
WHERE NOT EXISTS (SELECT * FROM A)
if NOT EXISTS doesn't work in your DBMS you could also use a left outer join comparing the rows columns values.
SELECT
A.*
from
A left outer join B
on A.col = B.col and ....

Copy specific columns from one table to another table, and include the source tablename

I have this newly created table in SQL Server with 3 columns ID, Name, Source.
Basically this table will be populated with data from other different tables, each specifically taking in their record IDs and record Names. I believe this can be easily achieved with an INSERT INTO SELECT statement.
I would like to find out on how to populate the Source column. This column is supposed to indicate which table the data came from. For example, Source in table A has 3 records, which I then copied the ID and Name columns from this table, and put it into my destination table.
At the same time, the 3 new records will have their Source column set, indicating it came from Table A. Then I will proceed to do the same for other tables.
You can use the constant string as follows:
INSERT INTO your_table
SELECT id, name, 'TableA' as source
FROM tableA

How to update numerical column of one table based on matching string column from another table in SQL

I want to update numerical columns of one table based on matching string columns from another table.i.e.,
I have a table (let's say table1) with 100 records containing 5 string (or text) columns and 10 numerical columns. Now I have another table that has the same structure (columns) and 20 records. In this, few records contain updated data of table1 i.e., numerical columns values are updated for these records and rest are new (both text and numerical columns).
I want to update numerical columns for records with the same text columns (in table1) and insert new data from table2 into table1 where text columns are also new.
I thought of taking an intersect of these two tables and then update but couldn't figure out the logic as how can I update the numerical columns.
Note: I don't have any primary or unique key columns.
Please help here.
Thanks in advance.
The simplest solution would be to use two separate queries, such as:
UPDATE b
SET b.[NumericColumn] = a.[NumericColumn],
etc...
FROM [dbo].[SourceTable] a
JOIN [dbo].[DestinationTable] b
ON a.[StringColumn1] = b.[StringColumn1]
AND a.[StringColumn2] = b.[StringColumn2] etc...
INSERT INTO [dbo].[DestinationTable] (
[NumericColumn],
[StringColumn1],
[StringColumn2],
etc...
)
SELECT a.[NumericColumn],
a.[StringColumn1],
a.[StringColumn2],
etc...
FROM [dbo].[SourceTable] a
LEFT JOIN [dbo].[DestinationTable] b
ON a.[StringColumn1] = b.[StringColumn1]
AND a.[StringColumn2] = b.[StringColumn2] etc...
WHERE b.[NumericColumn] IS NULL
--assumes that [NumericColumn] is non-nullable.
--If there are no non-nullable columns then you
--will have to structure your query differently
This will be effective if you are working with a small dataset that does not change very frequently and you are not worried about high contention.
There are still a number of issues with this approach - most notably what happens if either the source or destination table is accessed and/or modified while the update statement is running. Some of these issues can be worked around other ways but so much depends on the context of how the tables are used that it is difficult to provide a more effective generically-applicable solution.

SQL query to update one for one

I have table A with one to many relationship to table B. Whenever I do an update I create new record in table A with a new batch of records related created in table B. I had a bug in my code so when new items where being created the order of them was being reversed. I need to write a SQL query to update items in table B related to second item in table A to be the same as the ones related to first item in table A. I hope it makes any sense, will try to illustrate:
A1 -> B - 1234
A2 -> B - 4321
I want to update second set of values from table B to be the same as the ones related to A1 (1234)
You should not think of records order in database table. The only way to specify order of rows is ORDER BY clause in SELECT statement.
Make row_order or idx column in table B and put there required value for each item.
In some cases you will also get different order of B items for the first/source A record when selecting them without specifying order in ORDER BY clause.
Relational database table has no notion about neither row order nor column order.

Incrementing 2 fields after inserting values based on another table?

This is an extension of Insert values into table B based on column from table A?
From the above question, let's say in both the User_Permissions and Users table there's also 2 more columns recorded for audit purposes: a version column and a transaction_version column. When inserting the new row (which is based on a row from the Users table) into the User_Permissions table I need to take the value of the 2 columns in the Users table, increment it by 1 and then insert it into the User_Permissions table.
Is there an easy SQL query to do this? I suspect it'd have to do with another inline select but am unsure of the syntax.
You could use Triggers after insert to perform the needed updates