23 Kasım 2008 Pazar

SQL SERVER - Tek insert into ile birden fazla kayıt girebilmek - UNION ALL kullanımı

Ref:http://blog.sqlauthority.com/2007/06/08/sql-server-insert-multiple-records-using-one-insert-statement-use-of-union-all/

UNION
UNION ilişkili tabloların aynı tipte verileri olması kaydıyla DISTINCT ile getirmesidir. JOIN lemesi gibi.

UNION ALL
UNION ALL, UNION komutuna eşittir bir farkla, o da tüm değerleri seçmesi.

Union all çiftlenmiş kayıtlarıda getirir. Tüm kayıtlarını getirir ve tablolarını birleştirir.

A UNION komutu SELECT DISTINCT sonucunu getirir. Eğer tüm satırların eşsiz olarak ayrıştığını biliyorsanız UNION ALL kullanın, çünkü daha hızlıdır.

Örneğin:
Table 1 : First,Second,Third,Fourth,Fifth
Table 2 : First,Second,Fifth,Sixth

Result Set:
UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)
UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)


USE YourDB
GO
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('First',1);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Second',2);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Third',3);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Fourth',4);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Fifth',5);
GO


yerine

USE YourDB
GO
INSERT INTO MyTable  (FirstColSecondCol)
    
SELECT  'First' ,1
    
UNION ALL
SELECT  'Second' ,2
    
UNION ALL
SELECT  'Third' ,3
    
UNION ALL
SELECT  'Fourth' ,4
    
UNION ALL
SELECT  'Fifth' ,5
GO


sonuç:
INSERT : 5 saniye
INSERT SELECT UNION ALL : 40 milisaniye

SELECT INTO

Ref:reference

USE YourDB
GO
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('First',1);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Second',2);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Third',3);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Fourth',4);
INSERT INTO MyTable  (FirstColSecondCol)
        
VALUES ('Fifth',5);
GO

INSERT INTO SELECT

Ref: http://blog.sqlauthority.com/2007/06/08/sql-server-insert-multiple-records-using-one-insert-statement-use-of-union-all/

USE AdventureWorks
GO
    
----Create TestTable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
    
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstNameLastName)
    
SELECT FirstNameLastName
    
FROM Person.Contact
    
WHERE EmailPromotion 2
    
----Verify that Data in TestTable
SELECT FirstNameLastName
    
FROM TestTable
    
----Clean Up Database
DROP TABLE TestTable
GO