Insert ข้อมูลหลาย ๆ Record ใน Statement เดียว
ผมเกิดคำถามขึ้นมาว่า ถ้าหากเราต้องการที่จะ Insert ข้อมูลหลาย ๆ Record ใน SQL Server โดยการเขียนคำสั่งแค่คำสั่งเดียว มันจะทำได้ไหม
คำตอบก็คือ “ได้” ครับ มาลองดูกันว่ามันจะทำได้ยังไง
ข้อมูลที่จะ Insert มีอยู่ด้วยกัน 4 ชุดครับ
(‘ADM’, ‘Administrator’)
(‘USR’, ‘User’)
(‘TRN’, ‘Training’)
(‘REC’, ‘Recruit’)
วิธีที่ ๑ ใช้การ Insert แบบปกติ
1: USE YourDB
2: GO
3: INSERT INTO MyTable (FirstCol, SecondCol)
4: VALUES ('ADM', 'Administrator');
5: INSERT INTO MyTable (FirstCol, SecondCol)
6: VALUES ('USR', 'User');
7: INSERT INTO MyTable (FirstCol, SecondCol)
8: VALUES ('TRN', 'Training');
9: INSERT INTO MyTable (FirstCol, SecondCol)
10: VALUES ('REC', 'Recruit');
11: GO
วิธีที่ ๒ ใช้ Union all ครับ
USE YourDB
1: INSERT INTO MyTable (FirstCol, SecondCol)
2: SELECT 'ADM' ,'Administrator'
3: UNION ALL
4: SELECT 'USR' ,'User'
5: UNION ALL
6: SELECT 'TRN' ,'Training'
7: UNION ALL
8: SELECT 'REC' ,'Recruit'
9: GO
วิธีที่ ๓ วิธีนี้ทำได้ใน SQL 2008 Server เท่านั้นนะครับ
1: insert into MyTable values('ADM', 'Administrator'),
2: ('USR', 'User'),
3: ('TRN', 'Training'),
4: ('REC', 'Recruit');
ลองนำไปใช้ดูนะครับ
ไม่มีความคิดเห็น:
แสดงความคิดเห็น