首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

看看这段SQL代码怎么优化下 PK

2012-02-12 
看看这段SQL代码如何优化下 PKSET @vReturnTime (SELECT ReturnTime FROM car_arrive_info where ListId

看看这段SQL代码如何优化下 PK

SET @vReturnTime =(SELECT ReturnTime FROM car_arrive_info where ListId = @iListId AND (ReturnTime IS NOT NULL AND ReturnTime<>''))
SET @iiSn =(SELECT SN FROM CAR_ARRIVE_INFO WHERE ListId=@iListId AND ReturnTime=@vReturnTime)

IF EXISTS (SELECT ReturnTime FROM CAR_ARRIVE_INFO WHERE @vArriveTime < @vReturnTime AND ListId = @iListId AND SN <@iiSn )
BEGIN
UPDATE CAR_ARRIVE_INFO
SET ArriveTime = @vArriveTime,Distnce=@iDistnce,State=1,OutTime = @vArriveTime
WHERE ListId = @iListId AND SN = @iSn AND State=0 AND SN <@iiSn AND @vArriveTime < @vReturnTime
END

IF EXISTS (SELECT ReturnTime FROM CAR_ARRIVE_INFO WHERE @vArriveTime > @vReturnTime AND ListId = @iListId AND SN >= @iiSn)
BEGIN
UPDATE CAR_ARRIVE_INFO
SET ArriveTime = @vArriveTime,Distnce=@iDistnce,State=1,OutTime = @vArriveTime 
WHERE ListId = @iListId AND SN = @iSn AND State=0 AND SN >=@iiSn AND @vArriveTime >= @vReturnTime
END

[解决办法]
SELECT TOP 1 @vReturnTime=ReturnTime 
FROM DBO.car_arrive_info WITH(NOLOCK) 
WHERE ListId = @iListId 
AND (ReturnTime IS NOT NULL 
AND ReturnTime <> '') 
SELECT TOP 1 @iiSn=SN 
FROM dbo.CAR_ARRIVE_INFO WITH(NOLOCK) 
WHERE ListId=@iListId 
AND ReturnTime=@vReturnTime) 

IF EXISTS (SELECT ReturnTime 
FROM dbo.CAR_ARRIVE_INFO WITH(NOLOCK) 
WHERE @vArriveTime < @vReturnTime 
AND ListId = @iListId 
AND SN <@iiSn ) 
BEGIN 
UPDATE dbo.CAR_ARRIVE_INFO 
SET ArriveTime = @vArriveTime
,Distnce=@iDistnce
,State=1
,OutTime = @vArriveTime 
WHERE ListId = @iListId 
AND SN = @iSn 
AND State=0 
AND SN <@iiSn 
AND @vArriveTime < @vReturnTime 
END 

IF EXISTS (SELECT ReturnTime 
FROM dbo.CAR_ARRIVE_INFO WITH(NOLOCK) 
WHERE @vArriveTime > @vReturnTime 
AND ListId = @iListId AND SN >= @iiSn) 
BEGIN 
UPDATE dbo.CAR_ARRIVE_INFO 
SET ArriveTime = @vArriveTime
,Distnce=@iDistnce
,State=1
,OutTime = @vArriveTime
WHERE ListId = @iListId 
AND SN = @iSn 
AND State=0
AND SN >=@iiSn 
AND @vArriveTime >= @vReturnTime 
END

热点排行