September 6, 2022 at 6:24 pm
Looking for sample DDL syntax to CREATE a TABLE w/ a COLUMN that includes list of finite values.
For example, I only want 4 allowable SQL Versions stored in the column SQLServerVersion below. What is the correct DDL to accomplish this?
CREATE TABLE MyTable
(ID INT IDENTITY(1,1) NOT NULL,
MySQLServerName NVARCHAR(40) NOT NULL,
SQLServerVersion NVARCHAR(40) NOT NULL values ('SQL 2022', 'SQL 2019', 'SQL 2017', 'SQL 2014')
)
GO
(Yes, we know we should create a 2nd table w/ the list of valid SQL Versions but for this case, we want to use a contrained list of column valuesin the existing table. thx in advance)
September 6, 2022 at 7:25 pm
Recommend storing atomic values rather than denormalized lists. STRING_AGG() function makes it easy to return it to the client as a list if that's really required.
e.g., if you're trying to limit to a max of 4 versions, then add an ordinal column (tinyint is sufficient) with a check constraint that limits the ordinal to 1 through 4, and a unique constraint on MySqlServerName & Ordinal. You might also want a unique constraint on MySqlServerName & SqlServerVersion to prevent storing the same server/version more than once.
Out of curiosity, what do these allowable SQL Server versions mean/represent? Does MySqlServerName represent a host/VM rather than a SQL Server instance?
September 6, 2022 at 9:44 pm
Do you just need a check constraint on the column?
CREATE TABLE MyTable
(ID INT IDENTITY(1,1) NOT NULL,
MySQLServerName NVARCHAR(40) NOT NULL,
SQLServerVersion NVARCHAR(40) NOT NULL ,
CONSTRAINT CKMyTableSqlVersion CHECK (SQLServerVersion IN ('SQL 2022', 'SQL 2019', 'SQL 2017', 'SQL 2014'))
)
Or does the column contain a list of values that need to be constrained?
September 7, 2022 at 12:28 pm
thx all -- for your valuable feedback. Ed B, exactly what I was looking for! thank you.
September 16, 2022 at 2:33 pm
thx all -- for your valuable feedback. Ed B, exactly what I was looking for! thank you.
While there's likely no better way to do this, the trouble with something like this is that you're going to have to remember to change that check whenever Microsoft comes out with a new version of SQL Server. I hope you have a documented process somewhere that will help your memory. 😀
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply