Can I set 2 MB for maximum size of varbinary?

╄→尐↘猪︶ㄣ 提交于 2019-12-05 18:24:50

You could use a CHECK CONSTRAINT to ensure the size is below 2MB:

CREATE TABLE dbo.T
(
    ID INT IDENTITY,
    VarB VARBINARY(MAX)
);

ALTER TABLE dbo.T ADD CONSTRAINT CHK_T_VarB__2MB CHECK (DATALENGTH(VarB) <= 2097152);

Then when trying to insert something larger than 2 MB:

DECLARE @B VARCHAR(MAX) = '|';
INSERT dbo.T (VarB)
SELECT CONVERT(VARBINARY(MAX), REPLICATE(@B, 2097153));

You get an error:

The INSERT statement conflicted with the CHECK constraint "CHK_T_Column__2MB". The conflict occurred in database "TestDB", table "dbo.T", column 'VarB'.

There is no provision to specify varbinary(2097152), Once if you cross 8000 bytes,you should go for max keyword only.

It will consume only the memory you need (in your case it is 2MB) and it will store upto 2GB at max.

varbinary(max) = 2 gigabytes.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!