I need to have a sql function which takes a valid SQL Server date an returns the moon-phase for that date. I found a function, but unfortunaley it is in pl-sql which I have no understanding of, I can convert the code as is, but I have no idea how to get the julian date in SQL Server.
This is the skeleton function I want to use
IF OBJECT_ID (N'dbo.fn_phaseOfMoon', N'FN') IS NOT NULL
DROP FUNCTION dbo.fn_phaseOfMoon;
GO
CREATE FUNCTION dbo.fn_phaseOfMoon (@DATE datetime)
RETURNS VARCHAR(30) AS
BEGIN
RETURN 'NA';
END
GO
The pl-sql code is located here, can someone please point me in the right direction, or help converting the code?
This is Java code that I've changed into MSSQL. See if does the trick for you.
CREATE FUNCTION dbo.fn_phaseOfMoon (@Date datetime)
RETURNS INT
BEGIN
Declare @y int,
@m int,
@d int,
@c int,
@e int,
@b int,
@jd float
Select @y = DatePart(yy, @Date), @m = DatePart(mm, @Date), @d = DatePart(dd, @Date)
/*
calculates the moon phase (0-7), accurate to 1 segment.
0 = > new moon.
4 => full moon.
*/
if (@m < 3)
Select @y = @y - 1, @m = @m + 12
Select @m = @m + 1;
Select @c = 365.25 * @y, @e = 30.6 * @m
Select @jd = @c+@[email protected] /* jd is total days elapsed */
Select @jd = @jd / 29.53 /* divide by the moon cycle (29.53 days) */
Select @b = convert(int, @jd) /* int(jd) -> b, take integer part of jd */
Select @jd = @jd - @b /* subtract integer part to leave fractional part of original jd */
Select @b = (@jd * 8) + 0.5 /* scale fraction from 0-8 and round by adding 0.5 */
if @b = 8
Select @b = 0 /* 0 and 8 are the same so turn 8 into 0 */
return @b
END
I don't know much about these stuff, so you have to check if the answer's is correct
Source of Java code : http://www.voidware.com/moon_phase.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With