1

我试图在我拥有的 MEMORY OPTIMIZED 表中保持完整性。该表中有一个指向另一个表的外键(唯一标识符)和一个表示记录是否处于活动状态的活动标志(位)。

如果传入记录与现有记录具有相同的外键,我想阻止插入发生,前提是现有记录处于活动状态(Active = 1)。

因为这是一个内存优化表,所以我无法做到这一点。我尝试创建一个唯一索引,发现它们在内存优化表中是不允许的。

更新:我最终使用存储过程来解决我的问题。存储过程将在插入或更新记录之前为我进行检查。

4

1 回答 1

0

大多数人使用触发器绕过内存表约束的限制。这里列出了许多示例:

https://www.mssqltips.com/sqlservertip/3080/workaround-for-lack-of-support-for-constraints-on-sql-server-memoryoptimized-tables/

特别是对于您的情况,这将模拟插入语句的唯一约束,但海报在上面的链接中也有更新和删除触发器的示例。

-- note the use of checksum to make a single unique value from the combination of two columns

CREATE TRIGGER InMemory.TR_Customers_Insert ON InMemory.Customers
 WITH EXECUTE AS 'InMemoryUsr'
  INSTEAD OF INSERT  
AS
 SET NOCOUNT ON
 --CONSTRAINT U_OnDisk_Customersg_1 UNIQUE NONCLUSTERED (CustomerName, CustomerAddress)
  IF EXISTS (
    -- Check if rows to be inserted are consistent with CHECK constraint by themselves
    SELECT 0
        FROM  INSERTED I
    GROUP BY CHECKSUM(I.CustomerName, I.CustomerAddress) 
    HAVING COUNT(0) > 1
    UNION ALL

       -- Check if rows to be inserted are consistent with UNIQUE constraint with existing data
    SELECT 0
        FROM  INSERTED I
    INNER JOIN InMemory.tblCustomers C WITH (SNAPSHOT)
      ON  C.ChkSum = CHECKSUM(I.CustomerName, I.CustomerAddress)
    ) 
    BEGIN
      ;THROW 50001, 'Violation of UNIQUE Constraint! (CustomerName, CustomerAddress)', 1
    END
  INSERT INTO InMemory.tblCustomers WITH (SNAPSHOT)
      ( CustomerID ,
       CustomerName ,
       CustomerAddress,
    chksum
      )
  SELECT  NEXT VALUE FOR InMemory.SO_Customers_CustomerID ,
      CustomerName ,
      CustomerAddress,
   CHECKSUM(CustomerName, CustomerAddress)
 FROM INSERTED
 GO
于 2019-11-20T21:18:08.220 回答