SQL Case不起作用

时间:2015-04-27 08:14:48

标签: sql sql-server-2008 function

我正在尝试将结果转换为varchar,但它一直给我这个错误,

代码

CREATE FUNCTION [dbo].[GetQuality](@FruitID VARCHAR(200))
RETURNS varchar(200)
AS
BEGIN
DECLARE @Result varchar(200);

WITH 
latest AS
(
    SELECT * FROM (SELECT TOP 1 * FROM Fruits_Crate WHERE FruitID like @FruitID ORDER BY ExpiryDate DESC) a
), 
result AS
(
    SELECT 
        latest.ExpiryDate as LatestExpiryDate, latest.Size as LatestSize, latest.Weight as LatestWeight,
        previous.ExpiryDate as PreviousExpiryDate, previous.Size as PreviousSize, previous.Weight as PreviousWeight,
        DATEDIFF(DAY, latest.ExpiryDate, CURRENT_TIMESTAMP) As LastMovementInDays,
        COALESCE((Select MovementInMonths from Fruits_Settings Where PolicyID like '178'),3) * 30 AS MM,
        CASE SIGN((latest.Weight * latest.Size) - (previous.Weight * previous.Size))
            WHEN 1 THEN 'Increased'
            WHEN 0 THEN 'Static'
            WHEN -1 THEN 'Decreased'
            ELSE 'Static'
        END AS Movement 
    FROM (SELECT TOP 1 * FROM (SELECT TOP 2 * FROM Fruits_Crate WHERE FruitID like @FruitID ORDER BY ExpiryDate DESC) x  ORDER BY ExpiryDate) previous
    FULL OUTER JOIN latest ON previous.FruitID = latest.FruitID
)

SELECT @Result = CAST( 
            CASE 
                WHEN LastMovementInDays <= MM AND (Movement = 'Increased' OR Movement = 'Decreased')
                    THEN Movement
                    ELSE 'Static'
                END) AS VARCHAR
FROM result;            
RETURN @Result

END

错误

  

Msg 1035,Level 15,State 10,Line 25'CAST'附近的语法不正确,   预期'AS'。

问题在于Cast我试图在这里使用。

3 个答案:

答案 0 :(得分:1)

您必须将AS VARCHAR置于CAST()功能中,如下所示

SELECT @Result = CAST( CASE 
                WHEN LastMovementInDays <= MM AND (Movement = 'Increased' OR Movement = 'Decreased')
                    THEN Movement
                    ELSE 'Static'
                END AS VARCHAR) 
FROM result;            

答案 1 :(得分:1)

您不需要指定CAST:

SELECT @Result = 
        CASE 
            WHEN LastMovementInDays <= MM AND (Movement = 'Increased' OR Movement = 'Decreased')
                THEN 'Movement'
                ELSE 'Static'
            END
FROM result;  

请注意,CASTvarchar的默认字符串为30个字符。但是,这不会导致代码示例出现问题,因为您已将@Result定义为VARCHAR(200),这可能会导致截断。运行例如:

SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR)

答案 2 :(得分:0)

更改此行:

END) AS VARCHAR

到这一个:

END AS VARCHAR)