1

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

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

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

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

简而言之,我想选择在其中或不在其中tblDefault的行defaultIDtblOtherCustomerUserID defaultIDtblOther

4

2 回答 2

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))
于 2013-01-24T02:37:41.970 回答
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)
    )
于 2013-01-24T02:58:58.457 回答