Here's a real-world schema:
CREATE TABLE [dbo].[Setting]
(
[ID] [BIGINT] NOT NULL,
[Module] [NVARCHAR](400) NOT NULL,
[Property] [NVARCHAR](400) NOT NULL,
[Value] [NVARCHAR](4000) NULL,
PRIMARY KEY CLUSTERED ( [ID] ASC )
)
And here's the INSERT statement I'm trying to execute:
INSERT INTO [Setting]
([ID],
[Module],
[Property],
[Value])
VALUES ((SELECT COALESCE(max(ID), 0) + 1
FROM [Setting]),
N'security.catalogs.integrated.integrated',
N'enable-integrated-authentication',
N'true')
For the life of me I cannot see anything special here, yet on at least two occasions this has failed on SQL Server 2008 R2 Express with the following error message:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
This INSERT statement operates on a completely empty table, no strange options were allegedly configured for SQL Server, no nothing.
How can this be happening? From my understanding of SQL Server, max cannot possibly return more than one row.

IDENTITYcolumn here? – Martin Smith Feb 25 at 21:42COALESCEexpands to aCASEstatement which can exhibit counter-intuitive behaviour; though this concern does not apply to the literal text in the question. I would also strongly echo Martin's comment about usingIDENTITYinstead. – Paul White Feb 26 at 3:11