SQL Server If语句Undeclared变量

时间:2013-05-08 07:06:53

标签: sql-server

我有以下代码:

CREATE FUNCTION db_owner.GetComp
(
    @CompID bigint,
    @ComponentType nvarchar(50)
)
RETURNS TABLE
AS
    RETURN /* SELECT ... FROM ... */

    IF (@ComponentType = 'WMCOMP') begin

        RETURN

        SELECT * 
        FROM WMCOMP 
        WHERE wmcompid = @CompID

    end
    ELSE IF (@ComponentType = 'ADECOMP') begin

        RETURN

        SELECT * 
        FROM ADECOMP 
        WHERE adecompid = @CompID

    end

尝试在Visual Studio中保存时,会显示以下错误:

  

IF

附近的语法不正确

我根本看不出有什么问题。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您在参数列表中缺少逗号:

CREATE FUNCTION db_owner.GetComp
(
    @CompID bigint,    --<---  need a comma here
    @ComponentType nvarchar(50)
)

答案 1 :(得分:2)

试试这个 -

CREATE FUNCTION db_owner.GetComp
(
      @CompID bigint
    , @ComponentType nvarchar(50)
)
RETURNS @Result TABLE (col1 INT, ...) 
AS
BEGIN

    INSERT INTO @Result (col1, ...)
    SELECT *
    FROM (
        SELECT *
        FROM dbo.WMCOMP
        WHERE wmcompid = @CompID
            AND @ComponentType = 'WMCOMP'

        UNION ALL

        SELECT *
        FROM dbo.ADECOMP
        WHERE adecompid = @CompID
            AND @ComponentType = 'ADECOMP'
    ) f

    RETURN

END