I have inadvertently used a couple of the SQL Server 2008 T-SQL features in a script containing a function which will be deployed to numerous customer databases, some of which will be SQL 2005.
An example of an offending statement:
create function dbo.fnThisWontWorkOnSQL2005
()
returns varchar(max)
as
begin
declare @intCounter int = 2
return @intCounter
end
select dbo.fnThisWontWorkOnSQL2005()
On a SQL2008 instance this will return 2.
On a SQL2005 instance this advises “Cannot assign a default value to a local variable.”
However, on a SQL 2005 database set by compatibility level running on a SQL2008 R2 instance the code runs happily and returns 2.
My issue arises as I am developing on a SQL2008R2 instance and I had assumed that setting the compatibility level of the target database to SQL Server 2005 would flag up any invalid T-SQL though this does NOT happen, or at least I can find nothing to prevent it happening.
Is anyone aware of a way to prevent this happening? I have searched variously but cannot find a way and it feels like a bug to me or do I always need to develop on the lowest SQL version I will be deploying to?
This is correct.
Compatibility level does not mean “run exactly like an older version”
It means “break less often while I fix the code”.
Never assume: check. This is what ALTER DATABASE says on MSDN says (my bold):
If you target SQL Server 2005, develop on SQL Server 2005. See developing SQL 2005 application using SQL 2008 server too