Insert Distinct Values from One Table into Another Table

Insert distinct values from one table into another table

Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:

INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;

There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower...

Insert into table with multiple select including select distinct from two tables

I think you want insert . . . select with join:

insert into Table3 (companyid, certno, expdate, createddate, is_null)
select distinct t2.companyid, t1.certno, t1.expdate, getdate(), 1
from Table1 t1 join
Table2 t2
on t1.company = t2.company
where t1.company like '%ABC%';

You can remove the where clause to insert all companies in one insert.

Select unique records and insert into another table avoiding duplicates in it

SQL DEMO

You can use GROUP BY and EXISTS in sql server like below :

insert into userto (username, date)
select distinct username, date from userfrom uf
where
not exists(select 1 from userto where username=uf.username and date=uf.date)

SELECT DISTINCT values and INSERT INTO table

You can use INSERT INTO... SELECT statement on this,

INSERT INTO tableName (A, B, C)
SELECT A, B, MAX(C) + 1
FROM tableName
GROUP BY A, B
  • SQLFiddle Demo

Insert distinct records from column in Table1 into column table 2 into row where they match on a different column

You should use Merge Statement:

MERGE Inventory AS target
USING (SELECT Name, ProductName FROM Product) AS source (ProductID, ProductName)
ON (target.ProductID = source.ProductID)
WHEN MATCHED
THEN UPDATE SET Name = source.ProductName
WHEN NOT MATCHED
THEN INSERT (ProductID, Name)
VALUES (source.ProductID, source.ProductName);

You can find more here:https://msdn.microsoft.com/es-es/library/bb510625(v=sql.120).aspx



Related Topics



Leave a reply



Submit