如何在SQL Server中使用用户定义的表类型插入数据时避免重复记录

问题描述 投票:0回答:1

我试图使用我的.net应用程序在数据库中插入整个模型。我使用的是用户定义的表类型。

这是我的程序和用户定义的表;我正在使用SQL Server 2012。

CREATE TYPE [dbo].[TmpAccessRequest] AS TABLE
(
    [RequestId] [int] NULL,
    [RequesterID] [int] NULL,
    [RequestType] [int] NULL,
    [NextApprover] [int] NULL,
    [RequestStatus] [varchar](100) NULL,
    [Delegation] [int] NULL,
    [CreatedOn] [date] NULL,
    [CreatedBy] [varchar](100) NULL,
    [Description] [varchar](max) NULL,
    [IsSepecialRequest] [bit] NULL,
    [DelegationDetailID] [int] NULL,
    [IsActive] [bit] NULL,
    [IsDeleted] [bit] NULL,
    [ModifiedOn] [date] NULL
)
GO

CREATE PROCEDURE [dbo].[proc_SaveAccessRequest] 
   (@TmpAR TmpAccessRequest READONLY,
    @IsUAMSRequest BIT,
    @RequestID INT OUTPUT) 
AS  
BEGIN
    INSERT INTO tblRequests (RequesterID, RequestType, NextApprover, RequestStatus,
                             Delegation, CreatedOn, CreatedBy, Description,
                             IsSepecialRequest, DelegationDetailID, IsActive, IsDeleted, ModifiedOn)
        SELECT
            RequesterID, RequestType, NextApprover, RequestStatus,
            Delegation, CreatedOn, CreatedBy, Description,
            IsSepecialRequest, DelegationDetailID, IsActive, IsDeleted, ModifiedOn
        FROM
            @TmpAR  

    SET @RequestID = SCOPE_IDENTITY()

    --SET @RequestID=IDENT_CURRENT('tblRequests') 
    SELECT @RequestID
END

我想检查重复数据是否不应同时插入。那么我该如何使用用户定义的表类型呢?

sql-server stored-procedures sql-insert user-defined-types check-constraints
1个回答
0
投票

请查找对脚本所做的更改,以避免插入重复记录。所以我认为两列数据应该是唯一的,以避免重复用于用户理解目的

 CREATE PROCEDURE [dbo].[proc_SaveAccessRequest] 
(
  @TmpAR TmpAccessRequest READONLY,
  @IsUAMSRequest bit,
  @RequestID int OUTPUT
) 
AS  
BEGIN

     Insert into tblRequests
    (
       RequesterID
      ,RequestType
      ,NextApprover
      ,RequestStatus
      ,Delegation
      ,CreatedOn
      ,CreatedBy
      ,[Description]
      ,IsSepecialRequest
      ,DelegationDetailID
      ,IsActive
      ,IsDeleted
      ,ModifiedOn
    )
    SELECT
       RequesterID
      ,RequestType
      ,NextApprover
      ,RequestStatus
      ,Delegation
      ,CreatedOn
      ,CreatedBy
      ,Description
      ,IsSepecialRequest
      ,DelegationDetailID
      ,IsActive
      ,IsDeleted
      ,ModifiedOn
     FROM @TmpAR  
     WHERE NOT EXISTS ( SELECT 1 
                        FROM tblRequests i
                        INNER JOIN @TmpAR o  
                            ON i.RequesterID = o.RequesterID
                         AND i.RequestType = o.RequestType 
                         AND i.NextApprover = o.NextApprover)

     SELECT @RequestID = SCOPE_IDENTITY()

     SELECT @RequestID
END
© www.soinside.com 2019 - 2024. All rights reserved.