Why does MS SQL allow you to create an illegal column?
It a perfectly valid syntax for a computed column. Computed columns can be used to calculate some value on select without actually storing them, although the value can be persisted.
The reason why 1/0 is allowed, is because the actual computed column value not evaluated until runtime. For example the computed column can be defined as columna/columnb, the same error will occur if any row in columnb has a 0 and is , but only if that row/column was selected.
if object_id('tempdb..#t') IS NOT NULL
drop table #t;
CREATE TABLE #t
(a int
,b int
,div as (a/b)
);
INSERT INTO #t
values
(1,1)
,(2,0);
SELECT * FROM #t WHERE a = 1;
SELECT a from #t; -- NO ERRORS
SELECT * FROM #t WHERE a=2; --WILL RESULT IN AN ERROR
SELECT * FROM #t; --WILL RESULT IN AN ERROR
https://docs.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-2017
What you have created is a computed column and it is quite powerful and useful!
The expression can be anything. For instance, you could define:
CREATE TABLE [TableName] (
[ID] INT IDENTITY NOT NULL,
[Name] VARCHAR(50) NOT NULL,
NameLength as (LEN(Name))
);
This would create a column called NameLength
and it would always have the length of Name
when you refer to it -- no update
s, no triggers, no views. It just works.
You don't need a type because SQL Server can figure that out.
The error that you have can even be beneficial -- if you really want to enforce that users never use select *
.