如何为SQL Server编写此存储过程?

时间:2017-03-08 14:01:19

标签: java sql sql-server

如何为SQL Server写下这个存储过程?

显示此错误:

  

Msg 137,Level 15,State 2,Line 2       必须声明标量变量“@name”。

update login 
        set reg.name=@name
            reg.phone=@phone
            login.email_id=@email_id
            login.pwd=@pwd
            login.role=@role
    from  login  INNER JOIN reg on reg.r_id=login.l_id
    where reg.r_id=@ID

请帮助解决这个问题。

2 个答案:

答案 0 :(得分:0)

试试这个

update login 
        set reg.name=@name,
        reg.phone=@phone,
        login.email_id=@email_id,
        login.pwd=@pwd,
        login.role=@role 
    from  login  INNER JOIN reg on reg.r_id=login.l_id
    where reg.r_id=@ID`

答案 1 :(得分:0)

您无法使用单个SQL语句更新多个表中的列。 这样做的一种方法是创建使用多个更新语句来更新多个表的存储过程。 例如:

CREATE PROCEDURE p_UpdateLogin
(
    @id         INTEGER,
    @name       VARCHAR(10),
    @phone      VARCHAR(10),
    @email_id   VARCHAR(100),
    @pwd        VARCHAR(20), 
    @role       NVARCHAR(20)
)
AS
BEGIN
    BEGIN TRANSACTION [Tran1]
    BEGIN TRY
        UPDATE login 
           SET login.email_id = @email_id,
               login.pwd      = @pwd,
               login.role     = @role
          FROM login
               INNER JOIN reg
                 ON login.[l_id] = reg.[r_id]
         WHERE reg.[r_id] = @id

        UPDATE reg 
           SET reg.name     = @name,
               reg.phone    = @pwd
         WHERE reg.[r_id] = @id

    COMMIT TRANSACTION [Tran1]
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION [Tran1]
    END CATCH   
END

使用以下查询执行存储过程:

EXEC dbo.p_UpdateLogin @id = 50, @name = 'Saurabh',
     @phone = '1234567890', @email_id = 'demo@email.com',
     @pwd = '******', @role = 'Super';