Seeking to enforce more strict type safety and make it easier to detect mistakes, I would like to specify column types of my view explicitly.
But while this works:
CREATE VIEW [dbo].[myview] (
[a],
[b],
[c]
)
AS
SELECT 'a1', 'b1', 'c1';
this fails:
CREATE VIEW [dbo].[myview] (
[a] nvarchar(32) NOT NULL,
[b] nvarchar(32) NOT NULL,
[c] nvarchar(32) NOT NULL
)
AS
SELECT 'a1', 'b1', 'c1';
Is there a correct syntax for this?
SQL Server has to deduce the types – but you can force its hand if you need to:
As for the null/non-null side of things, again, SQL Server has to deduce this. If you have a column that you know will be
not nullbut SQL Server is getting it incorrect, you can wrap it in anISNULLstatement with a non-null second argument:And it will then describe the column as
not null. The second value doesn’t matter (after all, this is about my own assertion that the column will never be null), so long as it’s of a compatible type to the column.