3

我在从存储过程中调用存储过程时弄乱了条件语句。谁能帮我吗?

    CREATE PROCEDURE [dbo].[sp_Leaderboard] 

    @CompetitionId INTEGER

    AS

    DECLARE @Competition TABLE
    (CompId INTEGER,
    CompFormat NVARCHAR(10)
    )
    INSERT INTO @Competition
    SELECT CompetitionId, CompetitionFormatType
    FROM dbo.Competitions 
LEFT JOIN dbo.CompetitionFormat ON dbo.Competitions.CompetitionFormatId = dbo.CompetitionFormat.CompetitionFormatId
    WHERE CompetitionId = @CompetitionId


    CASE WHEN @Competition.CompFormat = "Strokes" THEN EXEC [dbo].[sp_Strokes] ELSE EXEC [dbo].[sp_Stableford]

此外,我知道我在我的代码中没有考虑到的一点是,我还需要将参数 @CompetitionId 带入我要去的任何程序中。

4

2 回答 2

4

为什么不直接使用IF语句?

IF (SELECT TOP 1 CompFormat FROM @Competition) = 'Strokes'
   BEGIN
       EXEC [dbo].[sp_Strokes] @CompetitionId 
   END
ELSE
   BEGIN
       EXEC [dbo].[sp_Stableford] @CompetitionId 
   END
于 2013-02-24T00:06:39.160 回答
2

您可以随心所欲地同时消除表变量。试试这个:

DECLARE @CompFormat varchar(50)

SELECT @CompFormat = CompetitionFormatType
FROM dbo.Competitions 
LEFT JOIN dbo.CompetitionFormat 
    ON dbo.Competitions.CompetitionFormatId = dbo.CompetitionFormat.CompetitionFormatId
WHERE CompetitionId = @CompetitionId

IF @CompFormat = 'Strokes'
BEGIN
    EXEC [dbo].[sp_Strokes] @CompetitionId
END
ELSE 
BEGIN
    EXEC [dbo].[sp_Stableford] @CompetitionId
END

或者,也许您应该创建一个以 为参数的新存储过程,@Competition.CompFormat然后在其中使用 IF 语句来决定从哪个表中查询。

于 2013-02-24T00:07:22.860 回答