开发者

MS-SQL Query - Update record retrieved via Stored Procedure

开发者 https://www.devze.com 2023-03-19 05:35 出处:网络
*UPDATE * The scope has now developed slightly, and I now need to retreive the fields \'Id, uri, linkTo\'. How does this change things???

*UPDATE *

The scope has now developed slightly, and I now need to retreive the fields 'Id, uri, linkTo'. How does this change things???

I'm using an MS-SQL 2005 db and have the following stored procedure;

CR开发者_运维问答EATE PROCEDURE dbo.getNewAds
(
@region
)
AS
BEGIN
SELECT TOP 1 Id, uri, linkTo FROM Adverts
ORDER BY NEWID()
WHERE adRegion = @region
END

I would like to then add '1' to the column named adShown in the same table, for the single result retrieved. What is the simplest / quickest means to do this within the same procedure?

Thanks in advance for any help you can offer.


try a single command:

CREATE PROCEDURE dbo.getNewAds
(
@region  --lazy, declare type!!
)
AS
BEGIN
    UPDATE TOP (1) Adverts
        SET adShown = adShown + 1
        OUTPUT INSERTED.ID
        WHERE adRegion = @region
END

UPDATE (Transact-SQL) says that:

TOP ( expression) [ PERCENT ]

Specifies the number or percent of rows that will be updated. expression can be either a number or a percent of the rows.

The rows referenced in the TOP expression that is used with INSERT, UPDATE, MERGE, or DELETE are not arranged in any order.

but in my limited testing (not many rows in the test table), it looks like it updates the same row each time, and that the OP is trying to update a different row each time.

so try this:

CREATE PROCEDURE dbo.getNewAds
(
@region  --lazy, declare type!!
)
AS
BEGIN
    DECLARE @ID int

    --select row to update
    SELECT TOP 1 
        @ID=Id 
        FROM Adverts
        WHERE adRegion = @region
        ORDER BY NEWID()


    --update and return result set in one command
    UPDATE TOP (1) Adverts
        SET adShown = adShown + 1
        OUTPUT INSERTED.ID
        WHERE ID=@ID
END


There is a quirky update syntax that will let you assign the value to a variable at the same time as performing an update, but I'm not going to show it to you because it is undocumented, unsupported, and I can't guarantee that it will continue to work in future versions of SQL Server. Here is the method I would recommend (assuming Id is PK or at least unique):

DECLARE 
  @Id INT, 
  @uri VARCHAR(2048),
  @linkTo VARCHAR(2048);

SELECT TOP 1 @Id = Id, @uri = uri, @linkTo = linkTo
  FROM dbo.Adverts
  WHERE adRegion = @region
  ORDER BY NEWID();

UPDATE dbo.Adverts
  SET adShown = adShown + 1
  WHERE Id = @Id;

SELECT Id = @Id, uri = @uri, linkTo = @linkTo;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号