SQL-Change values based on foreign keys (Input/Output) - sql

I am trying to make an MS SQL database, and I am quite new to this.
Lets say I have tables with columns
Table1=[Client_ID, Client_Name]
Table2=[Product, Client_ID]. (Client_ID is a FK to Table1)
Now I want to update data in Table 2 and I already have some info in Table 1. Is there a way to insert into T2 if I only know Product and Client_Name? (Somehow lookup client_ID in first table based on his name) What if I dont have that specific client in Table1 yet, can he be inserted during the insertion in T2?
Also I need to grab the data from T2, but I would want to see a table that is [Product, Client_Name]. Is that kind of lookup/replace possible in SQL?
I know I could try to solve these problems beforehand - I'm using Excel as a frontend for accessing my DB, but I hope there is an easier way to do this with SQL itself.

You can insert into Table 2 as follows
'You are passing #Product, #Client_Name
'First look for whether client name is present in table1
declare #clientId as integer;
select #clientId =Client_ID from Table1 where Client_Name=#Client_Name
if #clientId >0 'When there is client name in Table1
begin
insert into table2
values(#Product, #clientId)
end
else 'There is no client name, so we have to insert client name first then gets its id
begin
insert into table1
values(#Client_Name)
'Get id of newly added client, you can done this many way, but here is the simplest way like previous
select #clientId=Client_ID from Table1 where Client_Name=#Client_Name
'Now insert into table2
insert into table2
values(#Product, #clientId)
end
You can get the data the way you wanted by using Join
Select Table2.Product, Table1.Client_Name from table1 inner join table2 on table1.Client_ID = table2.Client_ID

Related

Inserting data from one database to another conditionally

In my MSQL server I have a first database with a table that contains ID and Data columns, a second database, which is a copy of the first, except the Data column is empty.
I would like to transfer data from the first database into the second, inserting into the row with the corresponding ID. I would like the query to look something like this, but I'm not sure about the syntax
INSERT INTO db1.dbo.Table (Data)
SELECT (Data)
FROM db2.dbo.Table
WHERE db1.dbo.Table(ID) = db2.dbo.Table(ID)
You can do an update on your second table like that:
UPDATE
t2
SET
t2.Data = t1.Data,
FROM
dbone.t1 AS t1
INNER JOIN dbtwo.t2 AS t2 ON t1.ID = t2.ID
If your second table is empty you can "copy" your data like that:
INSERT INTO dbone.t1 (ID, Data)
SELECT ID, Data
FROM dbtwo.t2

SQL Server trigger to update another table's column

I have two SQL Server tables called Table A and Table B. I have an application which inserts one row into Table A and three rows into Table B at the same time. As you can see in the screenshot below, we can link these inserted records based on their ID column in Table A and TransID column in Table B.
During the data insert on table B, if any rows out of 3 inserted rows contain a value called Printed in the Printed column, I want to update my Table A's relevant record's PrintStatus column to Printed as well.
How do I write a SQL Server trigger for this?
Well the best solution is to do this in your code(app) but if there is no way,
you can write a Trigger After Insert for Table B like the trigger example below:
CREATE TRIGGER [dbo].[YourTrigger] ON [dbo].[TableB]
AFTER INSERT
AS
DECLARE #id INT
BEGIN
SET NOCOUNT ON;
SET #id = (SELECT DISTINCT ID FROM Inserted)
IF EXISTS (SELECT * FROM Inserted WHERE Printed='Printed')
UPDATE TableA
SET PrintStatus='Printed'
WHERE ID = #id
END
May this help you
It could be correct for your problem : (not sure at 100%)
CREATE TRIGGER TriggerTableB
ON TableB
AFTER INSERT
AS
UPDATE TableA AS A
SET PrintStatus = 'Printed'
WHERE A.TranID = inserted.ID
AND 'Printed' = (SELECT MAX(I.Printed)
FROM inserted AS I)
I would recommend querying for the information:
select a.*,
(case when exists (select 1
from b
where b.id = a.tranid and b.printed = 'Printed'
)
then 'Printed'
end) as printstatus
from a;
This is simpler than writing a query and you can wrap this in a view.
From a performance perspective, an index on b(id, printed) should make this pretty fast -- and not slow down inserts.
A trigger can be quite complicated, if you want to take inserts, updates, and deletes into account. I prefer to avoid such complication, if possible.

How do I copy rows from one table to another in SQL?

I have been trying to copy the data listed in one table to another that are both located in the same database. However, every time I have everything entered, it runs the query and says 0 rows updated.
I have tried several variations in an attempt to get this to work. One such attempt is as listed below. I found this while researching in an attempt to get this done.
UPDATE
t1
SET
t1.column = t2.column
FROM
Table1 t1
INNER JOIN Table2 t2
ON t1.id = t2.id;
Any help on this would be greatly appreciated.
UPDATE will only modify records that already exist, if you want to insert rows that exist on another table use INSERT.
You can combine INSERT and SELECT to copy a whole table1 into a table2.
INSERT INTO table2 SELECT * FROM table1;
You can use INSERT IGNORE to copy only records that don't exist yet (based on unique keys).
You can also specify fields to copy in case the tables are different:
INSERT INTO table2 (id, first_name, last_name) SELECT id, name, surname FROM table1;

comparetwo SQL table record by record [duplicate]

I want to compare two tables recordby record. I have two cursor for each table. The code looks like this
Declare Cursor c1 for SELECT * from Table1
OPEN c1
While ##Fetch_status=0
Begin
Declare Cursor c2 for SELECT * from Table2
OPEN c2
WHILE ##Fetch_Status=0
Begin
/*Comparison happens here*/
END
END
When fecthing, must I specify which cursor I am fetching and how do I do that?
EDIT
For each record in Table1 I want to
Search Table2 for that record based on the primary key.
When it is found, I want to update the extra column values in Table2 based on the value of a column in table1.
When this record is missing in table2, I want to copy it
from table1 to table2 and set a default value of the extra column in
table2.
Open to other solutions (not restricted to cursors)
If tables have same column definition, the fastes way is just use 'except' clause:
SELECT * from Table1
except
SELECT * from Table2
also run it in opposite way:
SELECT * from Table2
except
SELECT * from Table1
You'll see the exact set difference:
EXCEPT and INTERSECT
Redgate has a great tool for this, if you'd rather just spend a few dollars:
You can get a free trial to see if it suits your needs.
Can't you just...
SELECT * FROM Table1 LEFT JOIN Table2 ON <your matching criteria>
...and then perform INSERT for the rows whose right "half" is NULL and UPDATE for those whose isn't?

SQL: compare two table record by record

I want to compare two tables recordby record. I have two cursor for each table. The code looks like this
Declare Cursor c1 for SELECT * from Table1
OPEN c1
While ##Fetch_status=0
Begin
Declare Cursor c2 for SELECT * from Table2
OPEN c2
WHILE ##Fetch_Status=0
Begin
/*Comparison happens here*/
END
END
When fecthing, must I specify which cursor I am fetching and how do I do that?
EDIT
For each record in Table1 I want to
Search Table2 for that record based on the primary key.
When it is found, I want to update the extra column values in Table2 based on the value of a column in table1.
When this record is missing in table2, I want to copy it
from table1 to table2 and set a default value of the extra column in
table2.
Open to other solutions (not restricted to cursors)
If tables have same column definition, the fastes way is just use 'except' clause:
SELECT * from Table1
except
SELECT * from Table2
also run it in opposite way:
SELECT * from Table2
except
SELECT * from Table1
You'll see the exact set difference:
EXCEPT and INTERSECT
Redgate has a great tool for this, if you'd rather just spend a few dollars:
You can get a free trial to see if it suits your needs.
Can't you just...
SELECT * FROM Table1 LEFT JOIN Table2 ON <your matching criteria>
...and then perform INSERT for the rows whose right "half" is NULL and UPDATE for those whose isn't?