Unique constraints for LARGE TEXT columns – SQL

Posted on November 5 2009 by Sachin Jain

Suppose you are storing URL in your table and you want to apply UNIQUE contraint but as SQL allows only 900 byte limit. how can you put unique constraint for larger text ??

For this you can create a computed CHECKSUM column which is an integer vale and put constraint on it.

Example as follows

CREATE TABLE messages (
ID INT NOT NULL PRIMARY KEY,
YOURTEXT VARCHAR(1024) NOT NULL,
YOURTEXT_checksum AS BINARY_CHECKSUM(YOURTEXT) — Added computed checksum column
)
GO

CREATE UNIQUE INDEX YOURTEXT_uk ON messages(YOURTEXT_checksum)
GO

INSERT INTO messages(ID, YOURTEXT) VALUES (1, ‘YOURTEXT 1′)
INSERT INTO messages(ID, YOURTEXT) VALUES (2, ‘YOURTEXT 2′)
INSERT INTO messages(ID, YOURTEXT) VALUES (3, ‘YOURTEXT 3′)
INSERT INTO messages(ID, YOURTEXT) VALUES (4, ‘YOURTEXT 3′)

- REsult

Msg 2601, Level 14, State 1, Line 5. Cannot insert duplicate key row in object ‘dbo.messages’ with unique index ‘YOURTEXT_checksum

VN:F [1.9.0_1079]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.0_1079]
Rating: 0 (from 0 votes)

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Powered by Sachin Jain

Powered by Olark