在存储过程中循环结果

时间:2013-01-24 02:14:37

标签: sql stored-procedures

如何在存储过程中循环一组选定结果并取出符合条件的结果。

如果它不需要循环或类似的东西我将如何实现这一目标?

所以我们假设我们有一个像这样的选择语句

SELECT DefaultID, Weight, Length, Height, Width FROM tblDefault 
WHERE CustomerID=@CustomerID AND  DeleteDateUTC is null

但是我怎样才能只获得符合条件的行

IF SELECT 1 FROM tblOther WHERE CustomerID=@CustomerID AND CustomerUserID=CustomerUserID 
AND DefaultID=@DefaultID returns 1 row 

OR SELECT 1 FROM tblOther WHERE CustomerID=@CustomerID AND DefaultID=@DefaultID returns nothing

简而言之,我希望选择tblDefaultdefaultID所在的行tblOther,其中CustomerUserID {{1} }}不在defaultID

2 个答案:

答案 0 :(得分:2)

要回答您的问题,请检查EXISTS(如果我正确理解您的问题 - 否则请编辑您的问题以使其更有意义)

SELECT d.DefaultID, d.Weight, d.Length, d.Height, d.Width 
FROM tblDefault d
WHERE CustomerID=@CustomerID AND  DeleteDateUTC is null
AND (EXISTS(SELECT 1 FROM tblOther WHERE CustomerID=@CustomerID AND CustomerUserID=@CustomerUserID 
     AND DefaultID=d.DefaultID) 
OR NOT EXISTS(SELECT 1 FROM tblOther WHERE CustomerID=@CustomerID AND DefaultID=d.DefaultID))

答案 1 :(得分:2)

我认为这是符合您条件的查询:

SELECT DefaultID, Weight, Length, Height, Width
FROM tblDefault td
WHERE CustomerID=@CustomerID AND  DeleteDateUTC is null and
     ( (SELECT count(*)
        FROM tblOther t
        WHERE CustomerID=@CustomerID AND t.CustomerUserID=td.CustomerUserID AND DefaultID=@DefaultID
       ) = 1 or
       not exists (SELECT 1 FROM tblOther WHERE CustomerID=@CustomerID AND DefaultID=@DefaultID)
    )