Skip to content
Advertisement

Putting the results of a query into new table in SQL Server

I want to insert query results into new table is there any way I can make changes in code so that it gets stored in a table.

My query:

SELECT DISTINCT TOP 5 a.DocEntry
    ,b.TrgetEntry
    ,b.itemcode
    ,a.DocNum AS 'Order No.'
    ,a.CardCode
    ,a.CardName
    ,b.DocDate AS [Delivery No.]
    ,c.targettype AS 'Ctargettype'
    ,c.trgetentry AS 'Ctargetentry'
    ,c.itemcode AS 'c-itemcode'
    ,c.docentry AS 'Cdocentry' a.CancelDate
    ,a.Project
    ,a.DocStatus
    ,b.ObjType
    ,a.ObjType
FROM ORDR a
INNER JOIN rdr1 b ON a.DocEntry = b.DocEntry
LEFT JOIN dln1 c ON c.TrgetEntry = b.DocEntry
    AND b.itemcode = c.ItemCode order by c.itemcode;

Advertisement

Answer

You can do it as it will create a new table and insert the records into that table. If you have already created table then you can give name and individual columns also for both insertion and selection.

SELECT *
INTO YourTableName
FROM (
    SELECT DISTINCT TOP 5 a.DocEntry
        ,b.TrgetEntry
        ,b.itemcode
        ,a.DocNum AS 'Order No.'
        ,a.CardCode
        ,a.CardName
        ,b.DocDate AS [Delivery No.]
        ,c.targettype AS 'Ctargettype'
        ,c.trgetentry AS 'Ctargetentry'
        ,c.itemcode AS 'c-itemcode'
        ,c.docentry AS 'Cdocentry' a.CancelDate
        ,a.Project
        ,a.DocStatus
        ,b.ObjType
        ,a.ObjType
    FROM ORDR a
    INNER JOIN rdr1 b ON a.DocEntry = b.DocEntry
    LEFT JOIN dln1 c ON c.TrgetEntry = b.DocEntry
        AND b.itemcode = c.ItemCode
    )

a

For using order by clause you can try something like this.

SELECT DISTINCT   
        Insured_Customers.FirstName, Insured_Customers.LastName,   
        Insured_Customers.YearlyIncome, Insured_Customers.MaritalStatus  
INTO Fast_Customers from Insured_Customers INNER JOIN   
(  
        SELECT * FROM CarSensor_Data where Speed > 35   
) AS SensorD  
ON Insured_Customers.CustomerKey = SensorD.CustomerKey  
ORDER BY YearlyIncome;

You can learn in detail about INTO Clause Here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement