Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Multiple Rows Into Temp Table With SQL Server 2012 [duplicate]

These StackOverflow questions here, here, and here all say the same thing, but I can't get it to run in SSMS or SQLFiddle

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

When I execute this is SSMS, the insert fails with the following message on the first line after VALUES

Msg 102, Level 15, State 1, Line 10
Incorrect syntax near ','.

This Fiddle runs without the # sign, and the schema executes successfully when the table name is #Names, but I get the following message when I try to select * from the table

Invalid object name '#NAMES'.: SELECT * FROM #NAMES

Does SQL Server 2012 support multiple inserts?


Update: Apparently accessing a 2005 server on SSMS 2012....

SELECT @@VERSION --Returns: Microsoft SQL Server 2005
like image 251
KyleMit Avatar asked Aug 01 '13 20:08

KyleMit


People also ask

How can I insert multiple rows in a table at a time in SQL?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

Can we insert duplicate rows in SQL?

The INSERT ON DUPLICATE KEY UPDATE is a MySQL's extension to the SQL standard's INSERT statement. When you insert a new row into a table if the row causes a duplicate in UNIQUE index or PRIMARY KEY , MySQL will issue an error.

How can I insert more than 1000 rows in SQL Server?

A table can store upto 1000 rows in one insert statement. If a user want to insert multiple rows at a time, the following syntax has to written. If a user wants to insert more than 1000 rows, multiple insert statements, bulk insert or derived table must be used.


1 Answers

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

like image 173
Sebastian Meine Avatar answered Sep 21 '22 16:09

Sebastian Meine