SQL Server - update multiple records using a stored procedure

1.4k views Asked by At

Being a super novice at this, I would like some guidance on this, please.

I need to compare two sets of data and update one set with a value. This is what I have so far.

PROCEDURE [dbo].[update_personnel_rank]
AS
    DECLARE @frsid VARCHAR
    DECLARE @officerid VARCHAR
    DECLARE @hrrank VARCHAR
    DECLARE @personnelrank VARCHAR
    DECLARE @farank VARCHAR

    DECLARE @rank VARCHAR(150)

    SET @rank = 'Admin Spec II'
BEGIN
    SET NOCOUNT ON;

    SELECT
        @frsid = hr.FRSID, 
        @officerid =  p.OfficerID,
        @hrrank =  hr.Rank,
        @personnelrank = p.Rank, 
        @farank =  r.FA_Rank
    FROM 
        [FireApp_REPL_DW_Data].[dbo].[MCFRSCombinedPersonnelandPimsStaff] hr 
    INNER JOIN
        [fh_reports].[dbo].[personnel_bk] p ON p.OfficerID = hr.FRSID
    INNER JOIN
        [fh_reports].[dbo].[Rank_Lookup_tbl] r ON r.FA_Rank = hr.Rank
    WHERE
        (p.rank <> hr.Rank OR p.rank = '')
        AND p.Rank = @rank

    UPDATE [fh_reports].[dbo].[personnel_bk]
    SET Rank = @farank
    WHERE OfficerID =  @officerid
END
GO

The select query returns 3 records and this stored procedure runs without any error, but it does not update the records. Since the select query returns 3 records, I think I need to change the parameter setting accordingly, but not sure how...

1

There are 1 answers

0
Russell Fox On BEST ANSWER

To @Sami's point, if you are not returning those variables, you do not need to set them and can instead just run the update:

USE [YourDatabase]
GO

SET NOCOUNT ON
GO

ALTER PROCEDURE [dbo].[update_personnel_rank]
    @rank VARCHAR(150) --= 'Admin Spec II'
AS 

BEGIN

    IF @rank IS NULL OR @rank = ''
        RAISERROR('Please enter a valid rank string.', 16, 1)

    UPDATE hr
        SET [Rank] = r.FA_Rank
    FROM    [FireApp_REPL_DW_Data].[dbo].[MCFRSCombinedPersonnelandPimsStaff]   [hr]
        INNER JOIN [fh_reports].[dbo].[personnel_bk]                            [p]
            ON [p].[OfficerID] = [hr].[FRSID]
        INNER JOIN [fh_reports].[dbo].[Rank_Lookup_tbl]                         [r]
            ON [r].[FA_Rank] = [hr].[Rank]
    WHERE [p].[rank] <> [hr].[Rank]
        AND ([p].[Rank] = @rank OR p.[Rank] = '')

END ;
GO