‘How to implement default constraints in the memory optimized table’ seems very simple to me and I tried to implement in the same way, as we usually do it in the disk based table. But the output was not as per the expectation. Let me show you the output.
USE hkNorthwind GO CREATE TABLE tbl_Product_Master ( [Product ID] INT not null primary key nonclustered hash with (bucket_count = 1024), [Product Name] NVARCHAR(100), [Creation Datetime] datetime default Getdate() ) WITH (MEMORY_OPTIMIZED = ON) GO
Msg 10770, Level 16, State 13, Line 3
The feature ‘default constraints’ is not supported with memory optimized tables.
Oooops.. I am unable to create a default constraint in memory optimized table.
So, can we create a default constraint column in memory optimized table ? The answer is No & Yes.
Why No: Because you cannot create a default constraint column in memory optimized table.
Why Yes:Because you can implement the default constraint functionality in memory optimized table using stored procedure.
Let me create the table & stored procedure to implement default constraints in the memory optimized table.
Step 1 :
First of all, you need to create a memory optimized table without any default constraint.
Given below is the script.
USE hkNorthwind GO CREATE TABLE tbl_Product_Master ( [Product ID] INT not null primary key nonclustered hash with (bucket_count = 1024), [Product Name] NVARCHAR(100), [Creation Datetime] datetime ) WITH (MEMORY_OPTIMIZED = ON) GO
Step 2 :
Once you have created the memory optimized table, create a stored procedure to insert records in it.
USE hkNorthwind GO CREATE PROCEDURE usp_Insert_Product_Master @ProductID int, @ProductName nvarchar(100) AS INSERT INTO tbl_Product_Master ([Product ID],[Product Name],[Creation Datetime]) VALUES (@ProductID,@ProductName,getdate())
Step 3 :
Insert the records using stored procedure in the memory optimized table.
Given below is the script.
USE hkNorthwind GO EXEC usp_Insert_Product_Master 1, 'SQL Server 2012' GO EXEC usp_Insert_Product_Master 2, 'SQL Server 2014'
Step 4 :
Just browse the table and check whether the default constraint is implemented or not.
USE hkNorthwind GO SELECT * FROM tbl_Product_Master GO --OUTPUT
Note : You can download the hkNorthwind database from here.
Reference : MSDN
Since users can still directly insert rows into tbl_Product_Master, you really haven’t created a default constraint. Remove everyone’s ability to insert into tbl_Product_Master (except for one user), then have the stored procedure EXECUTE AS that privileged user.
Now most users cannot insert directly into the table. Their only option for inserting into the table is through the stored proc