我有一个以字符串形式获取 sql 查询的过程。例子:
SELECT SUM(Refuse) FROM FOOD_DES WHERE Refuse > 1
但我只需要对满足条件的行求和。条件如下:
CONVERT(INT,RAND() * 100 ) <= @probability
但这不起作用(它总结了所有元素):
SELECT SUM(Refuse) FROM FOOD_DES WHERE Refuse > 1 AND
CONVERT(INT,RAND() * 100 ) <= @probability
所以接下来尝试:
SELECT SUM(Refuse) FROM FOOD_DES AS T CROSS APPLY fn_probability() AS F
CREATE FUNCTION fn_probability ( )
RETURNS @probabilityInfo TABLE ( Result INT )
AS
BEGIN
DECLARE @rand INT
SET @rand = ( SELECT TOP 1
RandValue
FROM RandView
)
IF @rand <= 80
INSERT INTO @probabilityInfo
( Result )
VALUES ( 1 )
RETURN
END
CREATE VIEW RandView AS SELECT CONVERT(INT, RAND() * 100) AS RandValue
但它也不起作用。任何的想法?:)