Tuesday, August 16, 2011

Using INSERT with the VALUE Clause and a SELECT Subquery


Using INSERT with the VALUE Clause & a SELECT Subquery

The data values supplied must match the column list. The number of data values must be the same as the number of columns, and the data type, precision, and scale of each data value must match those of the corresponding column. You can specify the data values in the following ways:
  • By using a VALUES clause to specify the data values for one row. For example:

    INSERT INTO MyTable (PriKey, Description)
           VALUES (123, 'A description of part 123.');
    
    For more information, see Inserting Rows by Using INSERT and Values.
  • By using a SELECT subquery to specify the data values for one or more rows, such as:

    INSERT INTO MyTable  (PriKey, Description)
           SELECT ForeignKey, Description
           FROM SomeView;
    
    For more information, see Inserting Rows by Using INSERT and SELECT Subqueries

To create a new table from values in another table, you can use SELECT INTO. For example:

SELECT LastName, FirstName, Phone
INTO dbo.PhoneList492
FROM dbo.Customers
WHERE Phone LIKE '492%'