Try .NET /elinq/
Powered by Try .NET

SQL Server INSERT INTO SELECT

1) Insert all rows from another table example

var rows = DbContext.Database.Execute((Customers customer, Addresses address) =>
{
    var set = address.@using((address.Street, address.City, address.State, address.ZipCode));

    INSERT().INTO(set);
    SELECT((customer.Street, customer.City, customer.State, customer.ZipCode));
    FROM(customer);
});

Console.WriteLine($"{rows} rows affected");

2) Insert some rows from another table example

var cities = new[] { "Santa Cruz", "Baldwin" };

var rows = DbContext.Database.Execute((Stores stores, Addresses address) =>
{
    var set = address.@using((address.Street, address.City, address.State, address.ZipCode));

    INSERT().INTO(set);
    SELECT((stores.Street, stores.City, stores.State, stores.ZipCode));
    FROM(stores);
    WHERE(cities.Contains(stores.City));
});

Console.WriteLine($"{rows} rows affected");

3) Insert the top N of rows

var rows = DbContext.Database.Execute((Customers customer, Addresses address) =>
{
    var set = address.@using((address.Street, address.City, address.State, address.ZipCode));

    INSERT(TOP(10)).INTO(set);
    SELECT((customer.Street, customer.City, customer.State, customer.ZipCode));
    FROM(customer);
});

Console.WriteLine($"{rows} rows affected");

4) Insert the top percent of rows

var rows = DbContext.Database.Execute((Customers customer, Addresses address) =>
{
    var set = address.@using((address.Street, address.City, address.State, address.ZipCode));

    INSERT(TOP(10).PERCENT()).INTO(set);
    SELECT((customer.Street, customer.City, customer.State, customer.ZipCode));
    FROM(customer);
});

Console.WriteLine($"{rows} rows affected");

< BACK | HOME