creating the index using WITH SCHEMABINDING option.
Msg 1949, Level 16, State 1, Line 1
Cannot create index on view . The function yields nondeterministic results. Use a deterministic system function, or modify the user-defined function to return deterministic results.
I could easily find out the reason for this error. He was using non-deterministic function in his view, which was leading to this error. Once the non-deterministic function was removed, the error disappeared.
The definition of the non-deterministic function is that it may return different results each time it is called with a specific set of input values. MSDN lists many functions as non-deterministic:
@@ERROR | FORMATMESSAGE | NEWID |
@@IDENTITY | GETANSINULL | PATINDEX |
@@ROWCOUNT | GETDATE | PERMISSIONS |
@@TRANCOUNT | GetUTCDate | SESSION_USER |
APP_NAME | HOST_ID | STATS_DATE |
CHARINDEX | HOST_NAME | SYSTEM_USER |
CURRENT_TIMESTAMP | IDENT_INCR | TEXTPTR |
CURRENT_USER | IDENT_SEED | TEXTVALID |
DATENAME | IDENTITY | USER_NAME |
Now if you are using any of the above function in your view, it will not allow you to create index on the view. You will have to remove the function before creating the view. Following is a quick example for the same:
USE TempDB
GO
-- Create view with non deterministic function GETDATE
CREATE VIEW TempView
WITH SCHEMABINDING
AS
SELECT GETDATE() AS CurrentTime, 1 FirstCol
GO
-- Check the data from the view
SELECT *
FROM TempView
GO
-- Attempt to create the view
CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredIndex_TempView] ON [dbo].[TempView]
(
FirstCol ASC
) ON [PRIMARY]
GO
/* Above query will throw following error
Msg 1949, Level 16, State 1, Line 1
Cannot create index on view 'tempdb.dbo.TempView'. The function 'getdate' yields nondeterministic results. Use a deterministic system function, or modify the user-defined function to return deterministic results.
*/
-- Alter View and remove non deterministic function GETDATE
ALTER VIEW TempView
WITH SCHEMABINDING
AS
SELECT 1 FirstCol
GO
-- Creating following view will work successfully
CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredIndex_TempView] ON [dbo].[TempView]
(
FirstCol ASC
) ON [PRIMARY]
GO
This is not the perfect solution as one need to remove the column from view; but if you want to create index, there is no way to create the index without removing the non-deterministic function.