Microsoft SQL Server 2012

Version of implementation Microsoft SQL Server of programming language SQL

Microsoft SQL Server 2012 (codenamed Denali) is a version of MS SQL Server released in March 2012.

Examples:

Hello, World! - SQL (15):

select 'Hello, World!';

Fibonacci numbers - SQL (17):

This example uses a kind of iterative definition of Fibonacci numbers, implemented with a recursive query. Each row of recursive query contains two consecutive numbers of the sequence, and next row is calculated as (last number, sum of numbers) of previous row. This way most numbers are stored twice, so only first number of each row is included in the result.

with fibonacci(a, b) as
(
 select 1, 1
  union all
 select b, a+b from fibonacci where b < 1000
)
SELECT cast(a as varchar)+', ' AS [text()]
  FROM fibonacci
   FOR XML PATH ('')

Factorial - SQL (16):

This example uses recursive factorial definition, implemented as a recursive query — a feature included in SQL Server 2005 and higher. Each row of recursive query contains two numeric fields — n and f = n!, and each row is calculated using the data of the previous row.

Note that starting with 2008 version you can calculate factorials only up to 12!. Trying to calculate 13! results in “Data truncation” error, i.e. the resulting value is too large for its datatype.

with factorial(n, f) as
(
 select 0, 1
  union all
 select n+1, f*(n+1) from factorial where n<16
)
select cast(n as varchar)+'! = '+cast(f as varchar)
  from factorial

Quadratic equation - SQL (497):

SELECT dbo.quadratic_equation(1,2,1)
SELECT dbo.quadratic_equation(1,2,3)

CREATE FUNCTION quadratic_equation (@a FLOAT
							,@b FLOAT
							,@c float  )
RETURNS varchar (100)
AS  
BEGIN

	DECLARE @ret  varchar(100);
	declare @delta float ;
	declare @denom float ;
	select @delta=(POWER(@b,2)-4*@a*@c);
	select @denom=(2*@a);
	if (@delta>=0)    
		BEGIN
			DECLARE @x12 FLOAT;
			SELECT @x12=((-@b+SQRT(@delta))/@denom);
			SELECT @ret='x1='+ CONVERT(varchar(100),@x12 )  
						+' x2='+ CONVERT(varchar(100),@x12 ) 
		END 
		ELSE 
			BEGIN  
				DECLARE @nat FLOAT;
				DECLARE @imm FLOAT;
				 
				SELECT @nat=((-@b)/@denom);
				SELECT @imm=((SQRT(-@delta))/@denom);
				SELECT @ret='x1='+ CONVERT(varchar(100),@nat)+'+i'+CONVERT(varchar(100),@imm ) 
							+' x2='+ CONVERT(varchar(100),@nat)+'-i'+CONVERT(varchar(100),@imm )
			end
	RETURN @ret ;

END;