我想要一个select语句,如果有任何列的列已过期,则会找到我。
这就是我没有运气的尝试,
Declare @FruitID INT;
SET @FruitID = '2876';
SELECT
dbo.IsFruitExpired(@FruitID, Fruits.CrateID) AS FruitExpired
FROM
Fruits WHERE Fruits.ID = @FruitID
结果
FruitExpired
0
0
1
0
所以我想返回1,如果有任何值为value = 1,否则返回0,我将在函数中添加这个select语句。
答案 0 :(得分:1)
您只需将MAX
功能应用于结果即可。如果只有1和0那么它将起作用。请注意,如果从函数返回BIT
类型,则需要强制转换:
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
如果返回BIT
:
SELECT @Result = MAX(CAST(dbo.IsFruitExpired(@FruitID, Fruits.CrateID) AS INT)) AS FruitExpired
FROM Fruits WHERE Fruits.ID = @FruitID
或者您可以使用EXISTS
:
IF EXISTS(SELECT * FROM Fruits WHERE dbo.IsFruitExpired(@FruitID, CrateID) = 1)
SET @Result = 1
ELSE
SET @Result = 0
答案 1 :(得分:0)
如果我正确地提出了您的问题,您想要检查Fruits表中的任何列,这可以通过使用动态sql和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;
答案 2 :(得分:0)
现在使用它,
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)