#T-SQL, 41 bytes / 11 versions = 3.7 score
T-SQL, 41 bytes / 11 versions = 3.7 score
SELECT MAX(cmptlevel)/10FROM sysdatabases
Note that this does not use a SQL "builtin, macro, or custom compiler flag"; that would be something like SELECT @@VERSION
or SELECT SERVERPROPERTY('productversion')
.
Instead, this looks up the highest "compatibility level" for all databases on the server. Existing databases on a server might have older compatibility levels, but the system database tempdb
is recreated each time the server is restarted, so will always have the compatibility level of the actual current version. (Using MAX
is shorter than including WHERE name='tempdb'
).
I divide by 10 so it returns the actual SQL version number.
I've successfully tested this on all versions between SQL 2005 and 2017, but I believe this will ultimately work in 11 distinct versions:
Version Number Release Name
6 SQL Server 6.0
6.5 SQL Server 6.5
7 SQL Server 7.0
8 SQL Server 2000
9 SQL Server 2005
10 SQL Server 2008 (or SQL Server 2008 R2)
11 SQL Server 2012
12 SQL Server 2014
13 SQL Server 2016
14 SQL Server 2017
15 SQL Server 2019 (Pre-release)
Let me know if anyone has SQL 2000 or older still running to see if this works as expected.
Note that my code uses a deprecated system table for widest compatibility, I'd normally use the newer sys.databases
system view introduced in SQL 2005.