To create a column of VARCHAR data type with a maximum of 10,000 characters, you declare the column as VARCHAR(MAX) data type and simply add a CHECK constraint to the column by checking the length of the column and making sure it is less than or equal to 10,000 characters. To illustrate, here's how it will look like: CREATE TABLE [dbo].[VarChar10000] ( [VarChar10000] VARCHAR(MAX) ) GO
ALTER TABLE [dbo].[VarChar10000] ADD CONSTRAINT [MaxLength10000] CHECK (DATALENGTH([VarChar10000]) <= 10000) GO With the column defined as VARCHAR(MAX), it can accept a string longer than 8,000 characters. But with the CHECK constraint, it will not allow a string with a length of more than 10,000 characters. To verify that the column will not allow a string of more than 10,000 characters, try executing the following INSERT command, which will insert a string value of 11,000 characters: INSERT INTO [dbo].[VarChar10000] ( [VarChar10000] ) VALUES (REPLICATE(CAST('A' AS VARCHAR(MAX)), 11000))
The following error will be shown when the INSERT statement above is executed: Server: Msg 547, Level 16, State 1, Line 1 The INSERT statement conflicted with the CHECK constraint "MaxLength10000". The conflict occurred in database, table "dbo.VarChar10000", column 'VarChar10000'. The statement has been terminated.
|
No comments:
Post a Comment