Cómo puedo insertar varias filas SIN repetir el " INSERTAR EN dbo.¿Parte de la declaración?


Sé que he hecho esto hace años, pero no puedo recordar la sintaxis, y no puedo encontrarla en ninguna parte debido a que tengo toneladas de documentos de ayuda y artículos sobre "importaciones a granel".

Esto es lo que quiero hacer, pero la sintaxis no es exactamente correcta... por favor, alguien que ha hecho esto antes, ayúdame:)

INSERT INTO dbo.MyTable (ID, Name)
VALUES (123, 'Timmy'),
    (124, 'Jonny'),
    (125, 'Sally')

Sé que esto es cerca de la sintaxis correcta. Podría necesitar la palabra "BULK" ahí, o algo, que no puedo recordar. Alguna idea?

Necesito esto para base de datos SQL Server 2005. He intentado este código, en vano:

DECLARE @blah TABLE
(
    ID INT NOT NULL PRIMARY KEY,
    Name VARCHAR(100) NOT NULL
)

INSERT INTO @blah (ID, Name)
    VALUES (123, 'Timmy')
    VALUES (124, 'Jonny')
    VALUES (125, 'Sally')

SELECT * FROM @blah

Estoy recibiendo Incorrect syntax near the keyword 'VALUES'.

Author: Robert Harvey, 2010-04-12

13 answers

INSERT INTO dbo.MyTable (ID, Name)
SELECT 123, 'Timmy'
UNION ALL
SELECT 124, 'Jonny'
UNION ALL
SELECT 125, 'Sally'

Para SQL Server 2008, puede hacerlo en una cláusula de VALORES exactamente según la instrucción en su pregunta (solo necesita agregar una coma para separar cada instrucción de valores)...

 290
Author: gbn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 13:05:00

Su sintaxis casi funciona en SQL Server 2008 (pero no en SQL Server 20051):

CREATE TABLE MyTable (id int, name char(10));

INSERT INTO MyTable (id, name) VALUES (1, 'Bob'), (2, 'Peter'), (3, 'Joe');

SELECT * FROM MyTable;

id |  name
---+---------
1  |  Bob       
2  |  Peter     
3  |  Joe       

1 Cuando la pregunta fue respondida, no se hizo evidente que la pregunta se refería a SQL Server 2005. Dejo aquí esta respuesta, ya que creo que sigue siendo pertinente.

 441
Author: Daniel Vassallo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-03 14:11:19

Si sus datos ya están en su base de datos puede hacer:

INSERT INTO MyTable(ID, Name)
SELECT ID, NAME FROM OtherTable

Si necesita codificar los datos, SQL 2008 y versiones posteriores le permiten hacer lo siguiente...

INSERT INTO MyTable (Name, ID)
VALUES ('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
 211
Author: George,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-30 22:22:54

Podrías hacer esto (feo pero funciona):

INSERT INTO dbo.MyTable (ID, Name) 
select * from
(
 select 123, 'Timmy'
  union all
 select 124, 'Jonny' 
  union all
 select 125, 'Sally'
 ...
) x
 13
Author: davek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-12 19:23:15

Usando la sintaxis INSERT INTO ... VALUES como en la respuesta de Daniel Vassallo hay una limitación molesta:

De MSDN

El número máximo de filas que se pueden construir insertando filas directamente en la lista DE VALORES es 1000

La forma más fácil de omitir esta limitación es usar una tabla derivada como:

INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name 
FROM (
   VALUES (1, 'a'),
          (2, 'b'),
          --...
          -- more than 1000 rows
)sub (ID, Name);

LiveDemo


Esto funcionará a partir de SQL Server 2008+
 13
Author: Lukasz Szozda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-08 14:20:16

Puedes usar una unión:

INSERT INTO dbo.MyTable (ID, Name) 
SELECT ID, Name FROM (
    SELECT 123, 'Timmy'
    UNION ALL
    SELECT 124, 'Jonny'
    UNION ALL
    SELECT 125, 'Sally'
) AS X (ID, Name)
 8
Author: Cade Roux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-12 19:24:30

Esto se ve bien para SQL Server 2008. Para SS2005 y anteriores, debe repetir la instrucción VALUES.

INSERT INTO dbo.MyTable (ID, Name)  
VALUES (123, 'Timmy')  
VALUES (124, 'Jonny')   
VALUES (125, 'Sally')  

EDIT:: Mi mal. Tienes que repetir el 'INSERTAR EN' para cada fila en SS2005.

INSERT INTO dbo.MyTable (ID, Name)  
VALUES (123, 'Timmy')  
INSERT INTO dbo.MyTable (ID, Name)  
VALUES (124, 'Jonny')   
INSERT INTO dbo.MyTable (ID, Name)  
VALUES (125, 'Sally')  
 6
Author: DaveE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-13 17:21:28

Sería más fácil usar XML en SQL Server para insertar varias filas, de lo contrario se vuelve muy tedioso.

Ver el artículo completo con explicaciones de código aquí http://www.cyberminds.co.uk/blog/articles/how-to-insert-multiple-rows-in-sql-server.aspx

Copie el siguiente código en sql server para ver un ejemplo.

declare @test nvarchar(max)

set @test = '<topic><dialog id="1" answerId="41">
        <comment>comment 1</comment>
        </dialog>
    <dialog id="2" answerId="42" >
    <comment>comment 2</comment>
        </dialog>
    <dialog id="3" answerId="43" >
    <comment>comment 3</comment>
        </dialog>
    </topic>'

declare @testxml xml
set @testxml = cast(@test as xml)
declare @answerTemp Table(dialogid int, answerid int, comment varchar(1000))

insert @answerTemp
SELECT  ParamValues.ID.value('@id','int') ,
ParamValues.ID.value('@answerId','int') ,
ParamValues.ID.value('(comment)[1]','VARCHAR(1000)')
FROM @testxml.nodes('topic/dialog') as ParamValues(ID)
 6
Author: Joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 00:16:20
USE YourDB
GO
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

O PUEDES USAR OTRA FORMA

INSERT INTO MyTable (FirstCol, SecondCol)
VALUES 
('First',1),
('Second',2),
('Third',3),
('Fourth',4),
('Fifth',5)
 6
Author: gngolakia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-02 07:36:27

He estado usando lo siguiente:

INSERT INTO [TableName] (ID, Name)
values (NEWID(), NEWID())
GO 10

Agregará diez filas con GUID únicos para ID y Nombre.

Nota: no termine la última línea (VAYA 10) con ';' porque lanzará un error: Se produjo un error de scripting fatal. Se encontró una sintaxis incorrecta al analizar GO.

 6
Author: valentinvs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-28 13:04:30

Correspondiente a INSERT (Transact-SQL) (SQL Server 2005) no puede omitir INSERT INTO dbo.Blah y tiene que especificarlo cada vez o usar otra sintaxis/enfoque,

 5
Author: abatishchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-13 17:33:15

Esto funciona muy rápido y eficiente en SQL. Supongamos que tiene la tabla Sample with 4 column a,b,c,d where a,b,d are int and c column is Varchar(50).

CREATE TABLE [dbo].[Sample](
[a] [int] NULL,
[b] [int] NULL,
[c] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[D] [int] NULL
)

Así que no puede insertar varios registros en esta tabla utilizando la siguiente consulta sin repetir la instrucción insert,

DECLARE @LIST VARCHAR(MAX)
SET @LIST='SELECT 1, 1, ''Charan Ghate'',11
     SELECT 2,2, ''Mahesh More'',12
     SELECT 3,3,''Mahesh Nikam'',13
     SELECT 4,4, ''Jay Kadam'',14'
INSERT SAMPLE (a, b, c,d) EXEC(@LIST)

También con C # usando SqlBulkCopy bulkcopy = new SqlBulkCopy(con)

Puede insertar 10 filas a la vez

   DataTable dt = new DataTable();
        dt.Columns.Add("a");
        dt.Columns.Add("b");
        dt.Columns.Add("c");
        dt.Columns.Add("d");
        for (int i = 0; i < 10; i++)
        {
            DataRow dr = dt.NewRow();
            dr["a"] = 1;
            dr["b"] = 2;
            dr["c"] = "Charan";
            dr["d"] = 4;
            dt.Rows.Add(dr);
        }
        SqlConnection con = new SqlConnection("Connection String");
        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(con))
        {
            con.Open();
            bulkcopy.DestinationTableName = "Sample";
            bulkcopy.WriteToServer(dt);
            con.Close();
        }
 2
Author: Charan Ghate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-19 21:31:20

Esto logrará lo que estás preguntando:

INSERT INTO table1 (ID, Name)
    VALUES (123, 'Timmy'), 
           (124, 'Jonny'), 
           (125, 'Sally');

Para futuros desarrolladores, también puede insertar desde otra tabla:

INSERT INTO table1 (ID, Name)
    SELECT 
         ID, 
         Name 
    FROM table2

O incluso de múltiples tablas:

INSERT INTO table1 (column2, column3)
    SELECT 
         t2.column, 
         t3.column
    FROM table2 t2
         INNER JOIN table3 t3
         ON t2.ID = t3.ID
 0
Author: Tigerjz32,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-18 17:08:04