在sql server 2005中检查列中是否存在值

时间:2010-01-20 04:30:38

标签: sql sql-server-2005 tsql loops

Hai guys,

我有一个名为 Is_Deleted 的列的表,我的查询是

select Is_Deleted from Stock where Stock.Mat_Id=1

alt text http://www.freeimagehosting.net/uploads/aaaff13d8a.jpg

现在我必须写一个条件来检查所有值是否 1 否则我必须终止我的循环..如何做到这一点?任何建议......

3 个答案:

答案 0 :(得分:1)

select exists(select 1 from Stock where Mat_Id = 1 and
  (is_deleted is null or is_deleted <> 1))

答案 1 :(得分:1)

这应该做你想要的。

IF EXISTS(SELECT 1 FROM (select DISTINCT Is_Deleted from Stock where Stock.Mat_Id=1) a WHERE Is_Deleted <> 1)
BEGIN
 -- Terminate the loop
END
ELSE
BEGIN
 -- Perform action
END

答案 2 :(得分:1)

只需存在一个简单的存在

IF EXISTS (SELECT * FROM Stock.Is_Deleted = 0 AND Stock.Mat_Id = 1)
...

如果你循环遍历不同的Mat_Ids ......

...
--Get first @Mat_Id
WHILE @Mat_Id IS NOT NULL
BEGIN
    IF EXISTS (SELECT * FROM Stock.Is_Deleted = 0 AND Stock.Mat_Id = @Mat_Id)
    BEGIN
       ...
    END
    SET @Mat_Id = NULL
    --Get next @Mat_Id
END
...