将所有查询(选择和删除)链接在一起

时间:2015-02-09 06:35:09

标签: sql sql-server

我正在尝试对以下查询进行一次声明(自动化)。

我所知道的UI中的提案ID。我像下面一样手动查询

select * from tblAssessment where ProposalID like '%0081/2013/0587B%'

select * from tblAssessmentVersion where AssessmentID=587

select * from tblIdentifiedThreatenedSpecies where AssessmentVersionID=731

delete from tblIdentifiedThreatenedSpecies where PercentGain=0 and AssessmentVersionID=731

一旦我知道了提案ID,我查询到tblassessment获取评估ID然后使用评估ID查询到评估版本ID以查找评估版本ID然后使用评估版本ID进入已识别物种表中删除percentgain列为0的记录。

感谢您的所有帮助,提前致谢

3 个答案:

答案 0 :(得分:1)

在一个子查询中加入所有SELECT

delete from tblIdentifiedThreatenedSpecies 
where PercentGain=0 and AssessmentVersionID in
(
  select av.Id 
  from 
  tblAssessmentVersion av 
  join tblAssessment a on a.Id = av.AssessmentID
  where a.ProposalID like '%0081/2013/0587B%'
)

答案 1 :(得分:1)

您可以使用DELETE FROM .. JOIN

DELETE s
FROM tblIdentifiedThreatenedSpecies s
INNER JOIN tblAssessmentVersion v
    ON v.AssessmentVersionID = s.AssessmentVersionID
INNER JOIN tblAssessment a
    ON a.AssessmentID = v.AssessmentID
WHERE
    a.ProposalID LIKE '%0081/2013/0587B%'
    AND PercentGain = 0

要检查要删除的行,请先SELECT

SELECT s.*
FROM tblIdentifiedThreatenedSpecies s
INNER JOIN tblAssessmentVersion v
    ON v.AssessmentVersionID = s.AssessmentVersionID
INNER JOIN tblAssessment a
    ON a.AssessmentID = v.AssessmentID
WHERE
    a.ProposalID LIKE '%0081/2013/0587B%'
    AND PercentGain = 0

答案 2 :(得分:0)

我希望这会奏效。

delete from tblIdentifiedThreatenedSpecies 
where PercentGain=0 and AssessmentVersionID=(
   select top 1 AssessmentVersionID from tblAssessmentVersion where AssessmentID=(
      select top 1 AssessmentID from tblAssessment where ProposalID like '%0081/2013/0587B%'
   )
);

如果查询返回多条记录,则使用top 1,这是您的查询不可选的。

谢谢。