SQL Server insert new rows ONLY based on multiple columns - sql-server

I searched in SO but couldn't find anything for my purpose. I need to insert unique rows ONLY from one table into another. I have:
table1
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1331 elm 04/01/2016 04/30/2016 05/01/2016 5656
table2
id name bookid bookname start_date end_date rel_date rel_id
1 horror 1221 rockys 04/01/2016 04/30/2016 05/01/2016 4545
2 horror 1441 elm 04/01/2016 04/30/2016 05/01/2016 5656
I need to insert into table1 the row with id = 2 in table2 AND also delete the row with id = 2 from table1, because bookid is different even though the rest of the columns match.
I tried following:
insert into table1
select * from table2
where not exists (select * from table2 where table1.id = table2.id
and table1.name = table2.name and table1.bookid = table2.bookid and
table1.bookname = table2.bookname and table1.start_date = table2.start_date
and table1.end_date = table2.end_date and table1.rel_date = table2.rel_date
and table1.rel_id = table2.rel_id)
Any way I can do all of this in one sql block?

In theory the following merge statement should achieve what you are looking for.
MERGE table1 [Target]
USING table2 [Source]
ON ([Target].[name] = [Source].[name]
AND
[Target].[bookname] = [Source].[bookname]
AND
[Target].[start_date] = [Source].[start_date]
AND
[Target].[end_date] = [Source].[end_date]
AND
[Target].[rel_date] = [Source].[rel_date]
AND
[Target].[rel_id] = [Source].[rel_id]
)
WHEN MATCHED AND ([Target].[bookid] <> [Source].[bookid]) THEN
UPDATE
SET [Target].[name] = [Source].[name]
,[Target].[bookid] = [Source].[bookid]
,[Target].[bookname] = [Source].[bookname]
,[Target].[start_date] = [Source].[start_date]
,[Target].[end_date] = [Source].[end_date]
,[Target].[rel_date] = [Source].[rel_date]
,[Target].[rel_id] = [Source].[rel_id]
WHEN NOT MATCHED THEN
INSERT(
[name]
,[bookid]
,[bookname]
,[start_date]
,[end_date]
,[rel_date]
,[rel_id]
)
VALUES
(
[Source].[name]
,[Source].[bookid]
,[Source].[bookname]
,[Source].[start_date]
,[Source].[end_date]
,[Source].[rel_date]
,[Source].[rel_id]
);
Note that there are some risks and limitations to this approach. If your [id] column has a uniqueness constraint, then it should be set as an identity column otherwise you will run into uniqueness violation errors. Also if [id] column value in table1 is different to [id] column in table2 then merge statement will keep the original [id] value from table1.
Basically this query simply updates your existing record in table1 with the matching record in table2 and insert new records from table2 into table1 if they don’t already exists.

All you should need to achieve your objective is this:
UPDATE T1
SET T1.bookid = T2.bookid
FROM Table1 T1
JOIN Table2 T2
ON T1.ID = T2.ID
However, to answer the question exactly as it was asked:
DELETE T1
FROM Table1 T1
JOIN Table2 T2
ON T1.ID = T2.ID
AND T1.bookid <> T2.bookid
INSERT INTO Table1
SELECT id, name, bookid, bookname, start_date, end_date, rel_date, rel_id
FROM Table2 T2
LEFT OUTER JOIN Table1 T1
ON T1.ID = T2.ID
AND T1.bookid = T2.bookid
WHERE T1.id IS NULL
Note that if your ID fields aren't unique, you'll need to add other conditions to the ON clauses.

If you are just concerned about updating the bookid value from table2, you can change the value of bookid with the below query
UPDATE t1 SET t1.bookid = t2.bookid
FROM table1 t1
JOIN table2 t2 ON t1.id = t2.id
If you think your id column is not unique in two tables, you might need to consider adding other matching columns in the JOIN.

Related

I have two tables Table1 and Table2 :I want to swap name column value From Table1 to Table2 and Table2 to Table1

[Below are two tables Table1 and Table2][1]
Table1:Column names id,name
Table2:Column names id,name
After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.
I tried to resolve the issue using below query:
update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));
But,it is not giving correct result.
You can't do this in a single pass, as you are overwriting the values you want to move in the next step. Here's a solution using a temporary table:
SELECT * INTO #temp FROM table1;
UPDATE t1 SET name = t2.name FROM table1 t1 INNER JOIN table2 t2 ON t2.id = t1.id;
UPDATE t2 SET name = t1.name FROM #temp t1 INNER JOIN table2 t2 ON t2.id = t1.id;
DROP TABLE #temp;
A little modification in your query and it worked.
create table temp1 as select * from table1;
update table1 set name = (select name from table2 where table2.id = table1.id);
update table2 set name = (select name from temp1 where temp1.id = table2.id);
Thanks,
Vinita Singh

SQL Server 2012 : copy a column from one table to another

I have two tables
TABLE1
skillid skillname
1 PM
2 SM
TABLE2
name skillid skillname
A 1
B 2
I want to get the skillname from table1 while inserting values into table2
Use the below query
UPDATE T2
SET T2.skillname = T1.skillname
FROM TABLE2 T2
INNER JOIN TABLE1 TI ON T1.skillid = T2.skillid
INSERT INTO Table2
SELECT #Name,
#skillid,
skillname
FROM Table1 T1
WHERE T1.skillid = #skillid
if you are using parameters to insert into table2.

Delete from SQL table where ID is found from conditions applied to another table

First of all, I don't know if the title is right but let me show you what I want and I will correct it as suggested.
So, I have 2 tables:
table1
ID, subid, name
table2
ID
What I want is to delete any element from table2 that has ID equal to subid in table1, where table1.name is equal to a specified value.
If I have these elements in table1
ID subid name
1 ... 1 ...... name1
2 ... 3 ...... name2
3 ... 2 ...... name1
4 ... 1 ...... name2
and these rows in table2
ID
1
2
3
4
I would like to remove those elements in table2 with ID = subid, when name = name1, which means elements 1 and 2.
Something like:
DELETE FROM table2
WHERE ID = (SELECT subid
FROM table1
WHERE NAME = "name1")
Is this possible?
You were very close.
You just need = ANY rather than = as the subquery can return more than one row SQL Fiddle.
DELETE
FROM table2
WHERE ID = ANY (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
Though this is more commonly expressed using IN
DELETE
FROM table2
WHERE ID IN (SELECT t1.subid
FROM table1 t1
WHERE t1.name = 'name1')
A couple of other changes I made to your posted query...
I always ensure that column references in subqueries use two part names to avoid unfortunate surprises.
You should use single quotes to delimit string literals so it works under default QUOTED_IDENTIFIER settings and is not interpreted as referencing a column called name1.
You can delete using joins as well, so yup very possible.
You can identify the (to be) deleted records first with:
select t2.*
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
then perform the delete as such:
delete t2
from table2 t2
inner join table1 t1 on t2.id = t1.subId
and t1.name = 'whatever'
#eckes see my fiddle with the syntax that I'm using to see it works: http://sqlfiddle.com/#!6/260a5

SQL Server stored procedure select, exists, multiple tables

Any method to do this?
Table1
1
2
3
4
5
Table2
3 (with the condition)
4 (without the condition)
I want to:
Select all records from Table1 if it exists in Table 2, where...(condition)
Select all records from Table1 if it not exists in Table2
Combine both select results. Sort all results with their created date.
For example, the result should be:
Result
1
2
3
5
Hopefully this can help.
SELECT t1.* from table1 t1
JOIN table2 t2
ON t1.ID = t2.ID
UNION ALL
SELECT t1.* from table1 t1 where ID in
(
SELECT t2.ID from table1 t1 except Select t2.ID from table2 t2
)
ORDER BY t1.CreatedDate
You can achieve this by doing:
SELECT t1.id
FROM Table1 t1
LEFT JOIN Table2 t2 on t1.id = t2.id
WHERE condition OR t2.id IS NULL
ORDER BY t1.CreatedDate;
See fiddle (I assumed condition to be t2.id!=4, but it can be anything else depending on other data in your tables).
There could be multiple solution.
One way
we can get the result set using two different queries and at last combine both of the result-set using UNION
Another way,
First statement is saying that get all the result set from TABLE1 if it exists in TABLE2 as well with some criteria (condition in where clause)
means using INNER JOIN we can achieve this
Second statement is saying get all the result set from TABLE1 which are not present in TABLE2
means along with INNER JOIN ed query also include the TABLE1's data if not present in TABLE2
here we can take the help of LEFT OUTER JOIN (taking TABLE1 on the left side)
Assumption: (condition: t1.Id != 4)
Let's try to understand the query using both of the above mentioned ways
---- -- --Step1 Create table and insert records
---- create table1 with Id int identity columsn
--CREATE TABLE Table1 (Id INT IDENTITY(1,1), CreatedDate smalldatetime default(getdate()));
--go
---- insert 1st 5 integers into Table1
--INSERT INTO Table1 DEFAULT VALUES
--go 5
---- create Table2 with Id int column
--CREATE TABLE Table2 (Id INT , CreatedDate smalldatetime default(getdate()));
--go
---- insert records 3,5 into Table2
--INSERT INTO Table2(Id) VALUES (3), (4);
-- -- -- Solution: one way
; WITH cteMyFirstResult AS
(
-- 2.1. Select all records from Table1 if it exists in Table 2, where...(condition)
SELECT
Id, CreatedDate
FROM Table1 AS t1
WHERE t1.Id IN (SELECT Id FROM Table2 AS t2)
AND t1.Id != 4 -- assumption it can be any condition
),cteMySecondResult AS (
-- 2.2. Select all records from Table1 if it not exists in Table2
SELECT
Id, CreatedDate
FROM Table1 AS t1 WHERE t1.Id NOT IN (SELECT Id FROM Table2 AS t2)
)
-- 2.3. Combine both select results. Sort all results with their created date.
SELECT
Id, CreatedDate
FROM cteMyFirstResult
UNION
SELECT
Id, CreatedDate
FROM cteMySecondResult
ORDER BY CreatedDate;
-- -- Solution: Another way (with bug)
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE t1.Id != 4
Order by T1.CreatedDate;
-- in this query we are using the criteria after doing the join operation.
-- thus after filtering out the result set based on JOIN Condition this condition will get applied
-- and if there is any null record in the Table1 for column Id (used in join) will not come in the final result-set
-- to avoid this we can include NULL check along with our criteria
-- -- Solution: Another way
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE ( t1.Id != 4 ) OR t1.Id IS NULL -- include all your criteria within small-barcket)
Order by T1.CreatedDate;
Thanks for all responses.
I come out with the answer I want:
SELECT *
FROM Table1 t1
WHERE NOT EXISTS(SELECT 1 FROM Table2 t2
WHERE t1.ID = t2.ID
AND t2.CIF_KEY = #CifKey
AND t2.STATUS <> ''3'')
AND (condition in where clause)

Insert column from one table to other using Join

I need to insert 3 columns from one table to another, using JOIN by 3 fields: name, surname and age
I need update column status, status1 and status2 in table_2 with values from table_1
IF
table_1.name = table_2.name
table_1.surname = table_2.surname
table_1.age= table_2.age
UPDATE t2
SET
t2.[status]=t1.[status]
,t2.[status1]=t1.[status1]
,t2.[status2]=t1.[status2]
FROM [table_1] t1
INNER JOIN [table_2] t2
ON (t1.name=t2.name AND t1.surname=t2.surname AND t1.age=t2.age)
As you mentioned in comments that these table from different databases, then please change only the two line like.
FROM [yourDataBase1Name].[dbo].[table_1] t1
INNER JOIN [yourDataBase2Name].[dbo].[table_2] t2
Just update the table with Join.
it will be something like this:
UPDATE t2
SET t2.status = t1.status,
t2.status1 = t1.status1,
t2.status2 = t1.status2
FROM t2 JOIN t1 on (t1.first_name = t2.first_name AND t1.last_name = t2.last_name AND t1.age = t2.age);
Look here for more information:SQL update query using joins
SQL Fiddle: http://sqlfiddle.com/#!3/b3951/1

Resources