简体   繁体   中英

How to write this stored procedure for SQL Server?

How to write down this stored procedure for SQL Server?

This error is shown:

Msg 137, Level 15, State 2, Line 2 Must declare the scalar variable "@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

please help with this problem.

Try this

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`

You can't update columns in multiple tables with a single SQL Statement. A way of doing this is to create the stored procedure that uses multiple update statements to update multiple tables. For example:

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

Use the query below to execute the stored procedure:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM