Perform insert for each row taken from a select? Perform insert for each row taken from a select? sql sql

Perform insert for each row taken from a select?


INSERT INTO table1 ( column1 )SELECT  col1FROM    table2

Like:

insert into property.portfolio_property_xref(     portfolio_id ,    building_id ,    created_date ,    last_modified_date)select    34,    building_id,    getdate(),    nullfrom    #temp_buildings


You will want to use INSERT INTO SELECT FROM (See SQL Fiddle with Demo)

insert into property.portfolio_property_xref(     portfolio_id ,    building_id ,    created_date ,    last_modified_date)SELECT 34 ,       building_id,       getdate(),       nullfrom    #temp_buildings


Kind of random, but I feel this may be useful to anyone who comes here to this question. Sometimes, i use Microsoft Excel VBA to generate portions of SQL Statements like listed above. I find this very useful when I am in situations where i am doing table construction and data transformation to set up a new job. this is a really simple example. It created a link between 2 separate unrelated systems. Then the link allowed me to build a new table in a warehouse environment that tied 3 unrelated systems together. Anyway, it allowed me to create > 5000 lines of SQL (for onetime use - and a small part of a much larger ETL task) in seconds.

Option ExplicitDim arow As IntegerDim acol As IntegerDim lrow As IntegerDim IsCellEmpty As StringDim CustNo As IntegerDim SkuLevel As IntegerSub SkuLevelUpdate()'find end ouf input filearow = 1acol = 1Do    IsCellEmpty = Cells(arow, acol).Value    arow = arow + 1Loop Until IsCellEmpty = ""lrow = arow - 1'Write SQLarow = 2acol = 5Do    CustNo = Cells(arow, 1)    SkuLevel = Cells(arow, 4)    Cells(arow, acol) = "INSERT INTO dbo.#TempSkuLevelRelationships (CustNo, SkuLevel) VALUES (" & CustNo & ", " & SkuLevel & ");"    arow = arow + 1Loop Until arow = lrowEnd Sub

Yes, I know all about SQL injection, etc. I create the spreadsheet(s), I copy/paste the data into larger SQL code for new construction, table modifications, and the like when the data does not currently reside in a SQL table