SQL 服务器 - 使用存储过程更新多条记录

SQL Server - update multiple records using a stored procedure

作为这方面的超级新手,我希望得到一些指导,请。

我需要比较两组数据并用一个值更新一组。这是我目前所拥有的。

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

select 查询 returns 3 条记录并且此存储过程运行没有任何错误,但它不更新记录。由于 select 查询 returns 3 条记录,我想我需要相应地更改参数设置,但不确定如何...

就@Sami 的观点而言,如果您不返回这些变量,则无需设置它们,只需 运行 更新即可:

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