I recently saw a tweet stating that you could prevent other developers from reading from a table using the SELECT * FROM TableName
by building your table in the following way:
CREATE TABLE [TableName]
(
[ID] INT IDENTITY NOT NULL,
[Name] VARCHAR(50) NOT NULL,
[DontUseStar] AS (1 / 0)
);
It's easy to see that using the SELECT *
here would try to read the blank column name as 1 divided by 0 (thus causing a divide by zero error), but without a datatype assigned to the column.
Why does SQL allow you to create a column with no assigned data type, with a name it knows will be illegal?
An invalid column name error in SQL means that the column name violates the conditions of the column name. If you reference an object that does not exist in the table or the name exists, but you did not reference it correctly, you will get this error.
Answer. For the columns in a table, there is a maximum limit of 1024 columns in a table. SQL Server does have a wide-table feature that allows a table to have up to 30,000 columns instead of 1024.
In Object Explorer, right-click the table to which you want to add columns and choose Design. Select the first blank cell in the Column Name column. Type the column name in the cell. The column name is a required value.
If you run the above query, you will get this error — “Ambiguous name column”. This means two columns have the same column name — that is the “Name” column. The SQL Machine is confused as to which “Name” out of the two tables you are referring to.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With