0

I want a select statement which will find me if there is any row with column expired value = 1.

This is what I am trying with no luck,

Declare @FruitID INT;
SET @FruitID = '2876';

 SELECT 
    dbo.IsFruitExpired(@FruitID, Fruits.CrateID) AS FruitExpired
 FROM 
    Fruits  WHERE   Fruits.ID = @FruitID 

Result

FruitExpired
0
0
1
0

So I want to return 1 if there is any row with value = 1 otherwise return 0, I am going to add this select statement in a function.

Mathematics
  • 7,314
  • 25
  • 77
  • 152
  • USE CASE STATEMENT http://stackoverflow.com/questions/5487892/sql-server-case-when-or-then-else-end-the-or-is-not-supported – A_Sk Mar 19 '15 at 09:20

3 Answers3

1

You can simply apply MAX function to result. If there are just 1 and 0 then it will work. Note that if you return BIT type from function you will need to cast:

Declare @FruitID INT;
SET @FruitID = '2876';
DECLARE @Result AS int

 SELECT @Result = MAX(dbo.IsFruitExpired(@FruitID, Fruits.CrateID)) AS FruitExpired FROM 
    Fruits  WHERE   Fruits.ID = @FruitID 

If BIT is returned:

 SELECT @Result = MAX(CAST(dbo.IsFruitExpired(@FruitID, Fruits.CrateID) AS INT)) AS FruitExpired
 FROM  Fruits  WHERE   Fruits.ID = @FruitID 

Or you can do it with EXISTS:

IF EXISTS(SELECT * FROM Fruits WHERE dbo.IsFruitExpired(@FruitID, CrateID) = 1)
   SET @Result = 1
ELSE
   SET @Result = 0
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
0

If I got your question correctly, you want to check on the any column in the Fruits table, this can be possible with the use of dynamic sql and the case statement:

DECLARE @tb NVARCHAR(255), @sql NVARCHAR(MAX), @FruitID NVARCHAR(5);
SET @FruitID = '2876';
SET @tb = N'dbo.[Fruits]';

SET @sql = N'SELECT 
                CASE';

SELECT @sql = @sql + N' WHEN ' + QUOTENAME(name) + ' = 1 THEN 1'
    FROM sys.columns 
    WHERE [object_id] = OBJECT_ID(@tb);

SELECT @sql = @sql + N' ELSE 0
                   END AS FruitExpired
               FROM ' + @tb + '
               WHERE Fruits.ID = ' + @FruitID
EXEC sp_executesql @sql;
chridam
  • 100,957
  • 23
  • 236
  • 235
0

Using this for now,

    Declare @FruitID INT;
    SET @FruitID = '2876';
    DECLARE @Result AS int

    IF
      (SELECT  COUNT(*)
          FROM Fruits
          WHERE dbo.IsFruitExpired(@FruitID, Fruits.CrateID) = 1 )
    = 1

     SET @Result = 0
   ELSE
     SET @Result = 1

   RETURN (@Result)
Mathematics
  • 7,314
  • 25
  • 77
  • 152