关键字' IF'附近的语法不正确用于表值函数

时间:2017-02-08 14:21:49

标签: sql-server function tsql if-statement

我试图创建一个表值函数,它接受两个参数," ThreadID"和" UserID",然后返回一个包含两个值的表," HasVoted"和" IsUpvote"。

CREATE FUNCTION HasVotedIsUpvote
(   
    @ThreadID int,
    @UserID int
)

RETURNS @returnTable TABLE 
(
    HasVoted int NOT NULL,
    IsUpvote int NOT NULL
)
AS
BEGIN 

DECLARE @HasVoted bit
DECLARE @IsUpvote bit


SELECT @HasVoted =
    CASE WHEN EXISTS (SELECT tv.IsUpvote
    FROM dbo.ThreadVotes as tv
    WHERE tv.ThreadID = @ThreadID
    AND tv.UserID = @UserID)
    THEN CAST(1 AS BIT)
    ELSE CAST(0 AS BIT)

IF @HasVoted = 1
BEGIN
    SELECT @IsUpvote =
    (SELECT tv.IsUpvote
    FROM dbo.ThreadVotes as tv
    WHERE tv.ThreadID = @ThreadID
    AND tv.UserID = @UserID)
END

BEGIN
    INSERT @returnTable
    SELECT @HasVoted, @IsUpvote
END

RETURN
END
GO

这对我来说似乎应该可行,但我收到错误消息:

Msg 156, Level 15, State 1, Procedure HasVotedIsUpvote, Line 38 [Batch Start Line 4]
Incorrect syntax near the keyword 'IF'.

3 个答案:

答案 0 :(得分:2)

您的CASE表达式似乎缺少END

SELECT @HasVoted =
    CASE 
       WHEN EXISTS (SELECT tv.IsUpvote
                    FROM dbo.ThreadVotes as tv
                    WHERE tv.ThreadID = @ThreadID
                          AND tv.UserID = @UserID)
          THEN CAST(1 AS BIT)
       ELSE CAST(0 AS BIT)
    END -- Should be used here

答案 1 :(得分:0)

中缺少END关键字
SELECT @HasVoted =
    CASE WHEN EXISTS (SELECT tv.IsUpvote
    FROM dbo.ThreadVotes as tv
    WHERE tv.ThreadID = @ThreadID
    AND tv.UserID = @UserID)
    THEN CAST(1 AS BIT)
    ELSE CAST(0 AS BIT)
    END  // <-- This one
祝你好运

答案 2 :(得分:0)

内联表值UDF不能包含除单个Select语句之外的任何语句。必须可以将UDF中的逻辑折叠到您使用它的任何外部SQL语句中,以便组合的SQL可以由查询处理器处理并作为组合的编译过程存储在进程缓存中。您编写的内容不是内联表值UDF。它是一个普通的过程UDF(编码为返回表变量),每次执行时都会重新编译。

内联表值UDF,otoh,只编译一次,因为其中的SQL与使用它的语句或过程的SQL结合,形成一个编译一次的单个组合SQL语句,存储在过程缓存中并反复使用。

试试这个:

<?php
    echo "<br>";
    $result = shell_exec('start file.bat');
    iconv("CP850","UTF-8",$result);
    echo "<pre>$result </pre>";
?>