Inserting multiple rows in a single SQL query?

39

Solution 1

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

Solution 2

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

Solution 3

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

Share:
39
josinalvo
Author by

josinalvo

Updated on October 18, 2020

Comments

  • josinalvo
    josinalvo over 3 years

    I have a state, that I go to by $state.go

    Lets call the state stateName, associated to a templateName, and the templateName calls controllerName.

    I have the impression that controllerName does not run every time I use $state.go(stateName) (this impression comes from using console.log inside controllerName)

    So far, my 'fix' is to use $scope.$on('$stateChangeSuccess' ... and check for stateName. But that feels brittle: if I change the name of the state I need to alter code inside the controller.

    My questions:

    1) Is it true that controllers are not always called when loading templateName ?

    2) Is there a way to ensure controllerName gets called every time? Or at least some function inside it?

    • Mikko Viitala
      Mikko Viitala almost 7 years
      Try $state.go(stateName, {}, { reload: true })
    • Rakeschand
      Rakeschand almost 7 years
      add your code of router