2014-11-03 49 views
1

我不知道我是否可以得到一些幫助,在SQL我有2表基於Person 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 

回答

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)