Home > SQL Tips > Multiple ways to INSERT records in a table

Multiple ways to INSERT records in a table

October 15, 2010 Leave a comment Go to comments

The following exercise shows multiple ways to INSERT records in a table, as the post title says.

USE [tempdb]
GO

CREATE TABLE sometable(a INT, b VARCHAR(20), c INT)
GO

-- Method #1 - Simple INSERT statement
INSERT sometable (a, b, c)
VALUES(1, 'New York', 123)
GO

DROP TABLE sometable

-- Method #2 - CREATE the table and INSERT records. This is minimally logged operation and faster than explicitly creating table and inserting records.
SELECT 1 a, 'New York' b, 334 c
INTO sometable
UNION
SELECT 2, 'London', 823
UNION
SELECT 3, 'Paris', 1124
UNION
SELECT 4, 'Munich', 2080
GO

-- Method #3
INSERT sometable (a, b, c)
 EXEC('SELECT 5, ''New York'', 234
  SELECT 6, ''London'', 923
  SELECT 7, ''Paris'', 1024
  SELECT 8, ''Munich'', 1980')
GO

-- Method #4
INSERT sometable (a, b, c)
 SELECT 9, 'New York', 334 UNION
 SELECT 10, 'London', 823 UNION
 SELECT 11, 'Paris', 1124 UNION
 SELECT 12, 'Munich', 2080
GO

-- Method #5 - More options in SQL Server 2008, by using the VALUES() constructor
INSERT sometable (a, b, c)
VALUES	(13, 'New York', 334),
		(14, 'London', 823),
		(15, 'Paris', 1124),
		(16, 'Munich', 2080))
GO

-- Method #6 - Yes you can also use SQL statements at column level inside the VALUES constructor
INSERT sometable (a, b, c)
VALUES	(18, 'New York', 334),
		(19, 'London', 823),
		((SELECT MAX(a)+1 FROM sometable), (SELECT b FROM sometable WHERE a=15), SELECT SUM(c) FROM sometable),
		(20, 'Munich', 2080))
GO

-- Now check the resultset
SELECT * FROM sometable

-- Final Cleanup
DROP TABLE sometable

More on VALUES constructor on MS BOL: http://technet.microsoft.com/en-us/library/dd776382.aspx

Advertisement
Categories: SQL Tips Tags:
  1. Akshay Saini
    April 11, 2016 at 10:12 pm

    There is a command to insert multiples value in one sql insert query by the use of ‘&’.
    Can u plzz tell me that insert command.???????

    • April 12, 2016 at 11:44 am

      Hi @Akshay, I think you are referring to Oracle. There you use “&” while inserting values in a table.

      • Akshay Saini
        April 12, 2016 at 10:55 pm

        Ohkk…
        Can u tell me tht one plzz????

  1. March 28, 2015 at 10:26 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: