Saturday, February 21, 2015

Drawing an Ellipse in SSMS


<= Building Sky Map in SSMS


Drawing a Parabola in SSMS =>



I was looking at orbits of planets, comets and asteroids and questioned myself if I can reproduce their tracks in SQL Server.

The first try is drawing Ellipse:

DECLARE @MP VARCHAR(MAX)='';

DECLARE @theta DECIMAL(8,4) = 0;-- angle that will be increased each loop
DECLARE @h DECIMAL(8,4) = 0;    -- x coordinate of center
DECLARE @k DECIMAL(8,4) = 0;    -- y coordinate of center
DECLARE @step DECIMAL(8,4) = 2 * PI()/100;  -- amount to add to theta each time (degrees)
DECLARE @a DECIMAL(8,4) = 10;    -- major axis
DECLARE @b DECIMAL(8,4) = 5;    -- minor axis

DECLARE @x1 DECIMAL(8,4), @y1 DECIMAL(8,4);
DECLARE @x2 DECIMAL(8,4) = @h + @a * COS(@theta);
DECLARE @y2 DECIMAL(8,4) = @k + @b * SIN(@theta);

WHILE @theta <= 2 * PI()
SELECT
    @x1 = @x2, @y1 = @y2,
    @x2 = @h + @a * COS(@theta),
    @y2 = @k + @b * SIN(@theta),
    @theta += @step,
    @MP = @MP + '('
        + CAST(@x1 as VARCHAR) +  ' '
        + CAST(@y1 as VARCHAR) + ','
        + CAST(@x2 as VARCHAR) +  ' '
        + CAST(@y2 as VARCHAR) + '),';

SELECT CAST('MULTILINESTRING(' + LEFT(@MP,LEN(@MP)-1) + ')' as geometry);

In this script you can change following parameters:
- Coordinates of the center of an ellipse - @h & @k;
- Lengths of Major and Minor axes' - @a & @b;
- Size of one step incremental angle - @step. That parameter also controls number of steps.

With a step size - 1/100 of a circle and axis' sizes 10 and 5 I've got that pretty Ellipse:


No comments:

Post a Comment