sql - 检索和更新存储过程中的顶行 - 由多个进程访问

标签 sql sql-server stored-procedures

我正在考虑创建一个被多个进程访问的存储过程,我想知道在两个解决方案之间,哪个更好,或者是否有第三个解决方案?

目标是找到在字段status 中具有最大值的记录。 status 字段包含十进制值,但定义为 varchar。一旦找到合适的记录,然后更新同一条记录(存储过程只能更新一条记录)。

存储过程会以select语句的形式返回cusip。

解决方案:01

Declare @Cusiptable(Cusip varchar(100));
UPDATE  cusiptbl
SET processingdate = GetDate() ,
Status = 'In Progress',
batchid = @batchid_given,
Output Inserted.Cusip into @Cusiptable
From 
(
 select top(1) Cusip from cusiptbl  where batchid = -1 
 order by cast(status as decimal(18,4)) desc  
) Seconds
where cusiptbl.cusip = Seconds.cusip

select Cusip from @Cusiptable

解决方案 02:

select top(1)  @CusipToBeUpdated = Cusip from cusiptbl 
        with (UPDLOCK)
        where batchid = -1 
        order by 
        (case when isnumeric(status) = 1 then 
            cast(status as decimal(18,7)) end) 
            desc

-- Update the status to given batchid and status as 'In Progress'
UPDATE  cusiptbl 
SET batchid = @batchid_given,
    processingdate = GetDate() ,
    Status = 'In Progress'
    where cusiptbl.cusip= @CusipToBeUpdated 
            and batchid = -1

 Select @CusipToBeUpdated Cusip

最佳答案

在为非数字值评估 order by cast(status as decimal(18,4)) 时,第一个查询将失败。

使用 isnumeric(status) = 1 重写它以防止错误:

From 
(
 select top(1) Cusip from cusiptbl  
 where batchid = -1  AND isnumeric(status) = 1
 order by cast(status as decimal(18,4)) desc  
) Seconds

假设事务隔离级别为读取提交或更高,这两种解决方案都应该有效。

从 varchar 转换为 numeric 会阻止使用索引(如果有的话),如果您的表很大,那么您可能会考虑向表中添加一个虚拟列,例如:

create table cusiptbl(
  ......
  status varchar(50),
  status_numeric as case when isnumeric(status) = 1 then 
            cast(status as decimal(18,7)) else null end
)

并在此虚拟​​列上创建索引:

create index num_status on cusiptbl( status_numeric )

或者可能是复合索引(因为您的查询使用 batchid=-1 条件过滤行,然后按状态对选定的行进行排序):

create index num_status_batch on cusiptbl( batchid, status_numeric )


然后重写查询并在其中使用虚拟列,例如:

From 
(
 select top(1) Cusip from cusiptbl 
 where batchid = -1 and status_numeric is not null
 order by status_numeric desc  
) Seconds

关于sql - 检索和更新存储过程中的顶行 - 由多个进程访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18242452/

相关文章:

mysql - 如何将shell脚本变量作为OUT参数传递给mysql存储过程?

c# - 从 C# 到 Php 的脚本推送不适用于应用程序

MySql存储过程: How to select from procedure table?

sql-server - 无法批量加载,因为无法打开文件。操作系统错误代码 3

php - 创建数组后用逗号将数组添加到 mysql varchar 行中

mysql - SQL SELECT SUM 所有行作为总计

sql-server - 选择多个静态值

python - 使用 Pandas/SQLAlchemy 导入日期时间

sql - MySQL foreach 替代过程

mysql - 使用聚合函数时如何从一行中获取其他列?