Pablo prez
Pablo prez

Reputation: 199

SQL Server : how to make a column optional?

I have a stored procedure in SQL Server 2012 that searches for data, then inserts it into a table. I also want to sort and decide the order of insertion without creating duplicates. The column that I want to sort by should not be inserted but I do not know if its possible to make a column optional..

This is my SQL:

INSERT INTO Plans (personID, Title, CreatedOn) 
    SELECT DISTINCT
        P.personID,
        A.title,
        A.CreatedOn,
        P.AppointmentTime    -- I want to sort by this column
    ... Join conditions
    ... ORDER BY P.AppointmentTime DESC

The code works great my only question is can how somehow exclude the P.AppointmentTime column from the insert? Since I am using distinct, I have to have it in the select list. Any suggestions would be great.

Upvotes: 0

Views: 382

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

You can use group by:

INSERT INTO Plans (personID, Title, CreatedOn) 
    Select distinct P.personID, A.title, A.CreatedOn
    from  ... Join conditions
    group by P.personID, A.title, A.CreatedOn
    order by max(P.AppointmentTime) desc

Upvotes: 1

Related Questions