SQL query to update one for one - sql

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.

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 ....

SQL query to insert IDs in tables

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

SQL Trigger Inserting from Multiple tables

I am trying to execute a query within a SQL trigger.
I have 4 tables A, B, C, D. Table A is a lookup list and contains roughly 1400 rows of data. Table B are values being input through an HMI with a timestamp. Table C is the table where my values are intended to go. Table D is a list of multipliers to use to multiply values from table A to table B (I am only using one multiplier from table D at the moment).
When a user inputs data into table B, that should trigger the procedure to get the values that were inserted (including the itemnumber) and relate the itemnumber to table A and use table D to multiply a few things together to send values to Table C. If I only input 3 rows of data in table B for example, I should only get three rows of data in table C. I am merely using table A to match the item number and get some data. But for some reason I am inserting way more records than intended, over 1600 rows.
Table D multipliers have a timestamp that does not match or have any correlation with any other table. So I am using a timestamp and selecting the multipliers that are closest to the timestamp from table B (some multipliers will change throughout time and I need a historical multiplier to correctly multiply the right things together)
Your help is most appreciated. Thank you.
Insert into TableC( ItemNumber, Cases, [Description], [Type], Wic, Elc, TotalElc, LbsPerCase, TotalLbs, PeopleRequired, ScheduleHours, Rated, Capacity, [TimeStamp])
Select
b.ItemNumber, b.CaseCount, a.ItemDescription, a.DivisionCode, a.workcenter,
a.LaborPercase as ELC, b.CaseCount * a.LaborPerCase * d.IpCg,
a.LbsPerCase, a.LaborPerCase * b.CaseCount as TotalLbs,
a.PersonReqd, b.Schedulehours, a.PoundRating,
b.ScheduleHours * a.PoundRating as Capactity, b.shift, GETDATE()
from
TableA a, TableB b, TableD
Where
a.itemnumber = b.itemnumber
and d.IpCG < b.TimeStamp
and b.CasesCount > 0
You do not reference the inserted or deleted tables that are available only in the trigger, so of course you are returning more records tha you need in your query.
When first writing a trigger, what I do is create a temp table called #inserted (and/or #deleted) and populate it with several records. It should match the design of the table that the trigger will be on. It is important to make your temp table have several input records that might meet the various criteria that affect your query (so in your caseyou want some where the case count would be 0 and some where it would not for instance) and that would be typical of data inserted into the table or updated init. SQL server triggers operate on sets of data, so this also ensures that your trigger can properly handle multiple record uiinserts or updates. A properly written trigger would have test cases you need to test to make sure everything happens correctly, your #inserted table should include records that meet all those test cases.
Then write the query in a transaction (and roll it back while you are testing) joining to #inserted. If you are doing an insert with a select, only write the select part until you get that right, then add the insert. For testing, write a select from the table you are inserting to in order to see the data you inserted before you rollback.
Once you get everything working, change the #inserted references to inserted, remove any testing code and of course the rollback (possibly the whole transaction depednig on what you are doing.) and add the drop and create trigger part of the code. Now you can test you trigger as a trigger, but you are in good shape becasue you know that it is likely to work from your earlier testing.

Select single row from database table with one field different and all other being same

I have a database table with 8 fields say Table(a,b,c,d,e,f,g,h).For some rows one of the field is different(say 4 different a values) while all other field values(b-h) in the schema are same.I have to make a table selecting just one rows from such rows with different a's but same b-h.That is I can select any one of the different a's and keep b-h same which they are and display it in table as 1 single row instead of 4.
SELECT MIN(a) a,b,c,d,e,f,g,h
FROM mytable
GROUP BY b,c,d,e,f,g,h

Need SQL to shift entries from one table to another

Heres the situation. I have 2 tables here of the schema:
ID | COMPANY_NAME | DESC | CONTACT
ID | COMPANY_ID | X_COORDINATE | Y_COORDINATE
The first tabel contains a list of companies and the second contacts coordinates of the companies as mentioned.
The thing is that I want to merge the data in this table with the data in another set of tables which already have data. The other tables have similar structure but are already propopulated with data. The IDs are autoincremental.
SO if we have lets say companies marked 1-1000 in table1 and companies marked 1-500 in table 2. We need it merged such that ID number 1 in table 2 becomes ID 1001 when migrated to the other table. And side by side we would also want to migrated the entries in the coordinates table as well in such a way that they map with the new ids of the table. Can this be done in SQL or do I need to resort to using a script here for this kind of work.
i`m not sure i understand how many tables are there and who is table 1 ,2, but the problem is pretty clear. i think the easy way is:
back up all your database before you start this process
add a column to the destination table that will contain the original id.
insert all the records you want to merge (source) into the destination table, putting the original id in the column you added.
now you can update the geo X,Y data using the old ID
after all is done and good you can remove the original id column.
EDIT: in reply to your comment , i`ll add teh code here, since its more readable.
adapted from SQL Books Online: insert rows from another table
INSERT INTO MyNewTable (TheOriginalID, Desc)
SELECT ID, Desc
FROM OldTable;
Then you can do an update to the new table based on values from the old table like so:
UPDATE MyNewTable SET X = oldTable.X , Y = oldTable.Y where
FROM MYNewTable inner JOIN OldTable ON MYNewTable.TheOriginalID = OldTable.ID