Selection and update in one stored procedure

I have a selected stored procedure, and I'm trying to make the results that it knocks also update the column with the name Downloadedand mark these lines as downloads.

For example, I am pulling 10 lines out of these 10 lines. I also want to update the column Downloadedto true in the same stored procedure. Is it possible?

This is my sp so far, it is dumping data.

ALTER PROCEDURE [dbo].[GetLeads]
@DateTo datetime = null,
@DateFrom datetime = null
AS
    SELECT name
         , lastname
         , title
         , company
         , address
         , address2
         , city
         , [state]
         , zip
         , country
         , stamptime

    FROM
        lead
    where
         ((@DateTo is null AND @DateFrom IS null) or (stamptime BETWEEN @DateTo AND @DateFrom))

Thank!

+5
source share
3 answers

Continuing the response to the Vulcanino comment, something like this:

ALTER PROCEDURE [dbo].[GetLeads]
@DateTo datetime = null,
@DateFrom datetime = null
AS
    UPDATE  
        lead 
    SET     
        Downloaded = 1 
    WHERE   
        ((@DateTo is null AND @DateFrom IS null) or (stamptime BETWEEN @DateTo AND @DateFrom))

    SELECT name
         , lastname
         , title
         , company
         , address
         , address2
         , city
         , [state]
         , zip
         , country
         , stamptime

    FROM
        lead
    where
         ((@DateTo is null AND @DateFrom IS null) or (stamptime BETWEEN @DateTo AND @DateFrom))
+4
source

You can just OUTPUTupdate the lines;

UPDATE lead
  SET Downloaded = 1
OUTPUT INSERTED.* 
  WHERE ((@DateTo is null AND @DateFrom IS null) or (stamptime BETWEEN @DateTo AND @DateFrom))

This update then returns the updated rows in a single expression.

+11

OUTPUT UPDATE.

http://blog.sqlauthority.com/2007/10/01/sql-server-2005-output-clause-example-and-explanation-with-insert-update-delete/

DECLARE @TEMPTABLE
(
    name <type>
    , lastname <type>
    , title <type>
    , company <type>
    , address <type>
    , address2 <type>
    , city <type>
    , state <type>
    , zip <type>
    , country <type>
    , stamptime <type>
)

UPDATE a
SET a.Downloaded = 1
OUTPUT Inserted.name, Inserted.lastname, Inserted.title, etc. INTO @TEMPTABLE
FROM lead a
WHERE ((@DateTo IS NULL AND @DateFrom IS NULL) OR (a.stamptime BETWEEN @DateTo AND @DateFrom))

SELECT * FROM @TEMPTABLE
+2

All Articles