'Add Check Constraint to Version number column

I'm trying to figure out how to add a CHECK constraint to the Version column to only accept NVARCHAR values with the format as such for example:

(Number.number.number)
10.4.1

or

(number.number.number. 3numbers)
10.4.1.111

This is my table:

CREATE TABLE dbo.Table
(
    ID int PRIMARY KEY IDENTITY,
    Version NVARCHAR(100) NOT NULL CHECK (Version)
)

Desired result would be, when a users updates the Version column, they must adhere to the defined formats.

For example, 11.3.4 would be acceptable and 12.4.3.444 would be acceptable.



Solution 1:[1]

Please try the following solution.

SQL

USE tempdb;
GO

DROP TABLE IF EXISTS dbo._tbl;

CREATE TABLE dbo._tbl (ID INT IDENTITY PRIMARY KEY, ver VARCHAR(30));
INSERT INTO dbo._tbl (ver) VALUES
('10.4.1'),
('10.4.1.111');

alter table dbo._tbl
add constraint codeCheck check (COALESCE(TRY_CAST(PARSENAME(ver, 1) AS INT) 
    + TRY_CAST(PARSENAME(ver, 2) AS INT) 
    + TRY_CAST(PARSENAME(ver, 3) AS INT), 0) + COALESCE(TRY_CAST(PARSENAME(ver, 1) AS INT)
    + TRY_CAST(PARSENAME(ver, 2) AS INT) 
    + TRY_CAST(PARSENAME(ver, 3) AS INT) 
     + TRY_CAST(PARSENAME(ver, 4) AS INT), 0) > 0);

-- it will fail
INSERT INTO dbo._tbl (ver) VALUES
('10.4.r');

-- it will work
INSERT INTO dbo._tbl (ver) VALUES
('17.7.77');

SELECT * FROM dbo._tbl;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yitzhak Khabinsky