如何在存储过程中使用 DECLARE

How to use DECLARE in a stored procedure

我正在创建一个存储过程,一旦记录是新的,它将在 table 中创建一个新行,如果记录存在于 table 中,则更新现有记录。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [procedurename]
    (@UserName [varchar](50),
     @UserEmail [varchar](50),
     @Role [varchar](30),
     @Status [varchar](30),
     @CreationDate [Date])
AS
    DECLARE @countRec INT

    SELECT @countRec = COUNT(*) 
    FROM [Synapse].[tablename] 
    WHERE [UserName] = @Username

BEGIN
    IF (@countRec = 0)
    BEGIN
        INSERT INTO [Synapse].[tablename] ([UserName], [UserEmail], [Role], [Status], [CreationDate])
        VALUES (@Username, @UserEmail, @Role, @Status, @CreationDate)
    END
    ELSE (@countRec > 0)
    BEGIN
        UPDATE [Synapse].[tablename]
        SET [Role] = @Role, 
            [Status] = @Status, 
            [CreationDate] = @CreationDate 
        WHERE [UserName] = @Username

        INSERT INTO [Synapse].[tablename]
    END

我收到以下错误:

Msg 103010, Level 16, State 1, Line 8
Parse error at line: 39, column: 7: Incorrect syntax near '@countRec'.

我不确定它为什么指向 countRec 变量。我能够毫无问题地使用类似的设置。有谁知道我在这里做错了什么?

亲切的问候,

罗格

您有许多语法错误 - 主要是:在进行任何声明或选择之前,您需要以 BEGIN 开始您的程序 - 最后缺少 END

试试这个:

CREATE PROCEDURE [procedurename]
    (@UserName [varchar](50),
     @UserEmail [varchar](50),
     @Role [varchar](30),
     @Status [varchar](30),
     @CreationDate [Date])
AS
BEGIN    -- put the "BEGIN" before you start declaring and selecting stuff
    DECLARE @countRec INT

    SELECT @countRec = COUNT(*) 
    FROM [Synapse].[tablename] 
    WHERE [UserName] = @Username

    IF (@countRec = 0)
    BEGIN
        INSERT INTO [Synapse].[tablename] ([UserName], [UserEmail], [Role], [Status], [CreationDate])
        VALUES (@Username, @UserEmail, @Role, @Status, @CreationDate)
    END
    -- either you have just an "ELSE" here - or if you want to 
    -- check another conditions, you need to use "ELSE IF ....."
    ELSE IF (@countRec > 0)
    BEGIN
        UPDATE [Synapse].[tablename]
        SET [Role] = @Role, 
            [Status] = @Status, 
            [CreationDate] = @CreationDate 
        WHERE [UserName] = @Username
    END
END   -- this was missing