基于Update / Insert语句的返回值

时间:2014-11-03 22:49:52

标签: sql-server

我想知道我是否可以在某些方面得到帮助,在SQL I有2个表格中它们之间的关系基于人员ID而我想写sp检查该人是否已经退出: 在一个语句中插入,否则执行更新语句。

我正在检查表是否值IsExit名称:GSACPeopleBadgeRequest

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spUpdateIDBadgeInfo] 
     @PersonID Int,
     @RequestedBy Int,
     @RequestedOn SmallDatetime,
     @BadgeStatusType Int,
     @ShippedLocationID Int,
     @Notes Varchar(500)= NULL,
     @Active bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from

    SET NOCOUNT ON;

DECLARE @retVal INT
SET @retVal = 0

DECLARE @CheckVal Bit
SET @CheckVal = 0


 IF @PersonID > 0
      BEGIN
        '#####################################How do this right.###########################
        @CheckVal  = select * from GSACPeopleBadgeRequest   where PersonID = @PersonID


    -- Check if there is any personID in GSACPeopleRequest, if not make a new insert
else
            Update  dbo.GSACPeopleBadgeRequest  
                 SET
                 RequestedBy = @RequestedBy,
                 RequestedOn = @RequestedOn,
                 BadgeStatusType = @BadgeStatusType,
                 ShippedLocationID = @ShippedLocationID ,
                 Notes = ISNULL(@Notes,@Notes),
                 Active = @Active
           WHERE PersonID = @PersonID

            -- Set the return value 
           SET @retVal = CAST(@@ROWCOUNT As int)

Select @retVal

END

END
GO

1 个答案:

答案 0 :(得分:0)

我认为你想要在没有找到@personid的情况下进行插入,否则如果存在然后更新,但在你的问题中,它会以相反的方式解释。试试这个。

IF NOT EXISTS (SELECT 1
               FROM   GSACPeopleBadgeRequest
               WHERE  PersonID = @PersonID)
  INSERT INTO GSACPeopleBadgeRequest
              (RequestedBy,RequestedOn,BadgeStatusType,ShippedLocationID,Notes,Active)
  SELECT @RequestedBy,
         @RequestedOn,
         @BadgeStatusType,
         @ShippedLocationID,
         Isnull(@Notes, ''),
         @Active
ELSE
  UPDATE dbo.GSACPeopleBadgeRequest
  SET    RequestedBy = @RequestedBy,
         RequestedOn = @RequestedOn,
         BadgeStatusType = @BadgeStatusType,
         ShippedLocationID = @ShippedLocationID,
         Notes = Isnull(@Notes, ''),
         Active = @Active
  WHERE  PersonID = @PersonID

-- Set the return value 
SET @retVal = Cast(@@ROWCOUNT AS INT)