如果SQL Where子句内部抛出错误

时间:2014-08-26 07:26:09

标签: sql sql-server tsql stored-procedures

我的存储过程就像这样

    alter  PROCEDURE ph_GetAllStaffAddressByCamp
    @CampCode  VARCHAR(20)

AS

IF NULLIF(@CampCode, '') IS NULL

    DECLARE @Year VARCHAR(2)
    EXEC cs_GetCurrentYear @Year OUTPUT

    SELECT DISTINCT [VolID], [CampID]  FROM [vStaffJobAndCamp]
 WHERE 
IF @CampCode IS NULL
    CampCode like @Year +%
ELSE
    CampCode = @CampCode

一切看起来都没问题,但它会像这样抛出编译错误

    Msg 156, Level 15, State 1, Procedure ph_GetAllStaffAddressByCamp, Line 14
Incorrect syntax near the keyword 'IF'.
Msg 102, Level 15, State 1, Procedure ph_GetAllStaffAddressByCamp, Line 15
Incorrect syntax near 'CampCode'.

有人知道我做错了吗?

4 个答案:

答案 0 :(得分:1)

IF不是有效的SQL关键字。因此,您无法在SELECT语句中使用它。

您可以在有效的SQL中表达这些条件,如下所示:

WHERE 
  (@CampCode IS NULL AND CampCode like @Year + '%')
  OR
  (@CampCode is NOT NULL AND CampCode = @CampCode)

答案 1 :(得分:1)

你在IF条款中忘记了BEGIN ... END。并且条件也是错误的

    alter  PROCEDURE ph_GetAllStaffAddressByCamp
    @CampCode  VARCHAR(20)

AS

IF NULLIF(@CampCode, '') IS NULL
BEGIN
    DECLARE @Year VARCHAR(2)
    EXEC cs_GetCurrentYear @Year OUTPUT

    SELECT DISTINCT [VolID], [CampID]  FROM [vStaffJobAndCamp]
 WHERE 
(@CampCode IS NULL and CampCode like @Year +%) OR
(@CampCode IS NOT NULL and CampCode = @CampCode)
END

答案 2 :(得分:0)

案例营销代码  当@CampCode为NULL时   那么CampCode就像@Year +% ELSE CampCode = @CampCode 结束

用例而不是where子句中的IF条件。

答案 3 :(得分:0)

如果你想要一个好的执行计划,你应该避免在WHERE子句中使用OR逻辑。

ALTER PROCEDURE ph_GetAllStaffAddressByCamp
    @CampCode  VARCHAR(20)
AS
IF @CampCode IS NULL OR @CampCode = ''
BEGIN
    DECLARE @Year VARCHAR(2)
    EXEC cs_GetCurrentYear @Year OUTPUT
    SELECT DISTINCT [VolID], [CampID]  FROM [vStaffJobAndCamp]
    WHERE CampCode LIKE @Year+'%'
END
ELSE
    SELECT DISTINCT [VolID], [CampID]  FROM [vStaffJobAndCamp]
    WHERE CampCode = @CampCode