如何在T-SQL中将波斯(shamsi)日期转换为公历?

问题描述 投票:0回答:1

我使用数据库中存储的大量数据来生成报告,我想知道是否存在快速选择表时将表中所有日期转换为波斯日期的方法。

有一些转换方法,但是它们不是基于SQL的,因此它们比仅SQL中的函数要慢。

所以,如果有人知道如何在SQL中进行转换,我将非常感谢他。

tsql date date-conversion
1个回答
0
投票

还有一天的搜寻,我决定采用自己的解决方式。

结果在这里:Enjoy:D

USE [Test]
GO
/****** Object:  UserDefinedFunction [dbo].[MyG2J]    Script Date: 10/11/2019 02:35:43 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[MyG2J](@inputDate DateTime)
                                        RETURNS nvarchar(max)
                                        begin
declare @mDay int,@mMonth int,@mYear int,@sDay int,@sMonth int,@sYear int,@mid int, @isMC bit=0,@isSC bit=0,@preSC bit = 0;

set @mDay=day(@inputDate);
set @mMonth=MONTH(@inputDate);
set @mYear=YEAR(@inputDate);

if @mYear%4=0
    set @isMC=1;
else
    set @isMC=0;

set @sYear=@mYear-622;

if (@sYear+1)%4=0
    set @preSC = 1;
else
    set @preSC=0;

select @mid=
case
    when @mMonth=1 then'20'
    when @mMonth=2 then'19'
    when @mMonth=3 then'20'
    when @mMonth=4 then'20'
    when @mMonth=5 then'21'
    when @mMonth=6 then'21'
    when @mMonth=7 then'22'
    when @mMonth=8 then'22'
    when @mMonth=9 then'22'
    when @mMonth=10 then'22'
    when @mMonth=11 then'21'
    when @mMonth=12 then'21'
end


if @isMC=1
    begin
        set @mid=@mid-1 
    end

if @mMonth=3 and @mDay=@mid
    set @sMonth=@mMonth+9;
else
begin
    if (@mMonth=3 and @mDay>@mid) or (@mMonth>3)
        begin
            set @sYear=@sYear+1;
            set @sMonth=@mMonth-3;
        end
    else
        set @sMonth=@mMonth+9;
end

if (@sYear+1)%4=0
    set @isSC = 1;
else
    set @isSC=0;

if @isMC=1
    BEGIN
        if @isSC=0
            if @mMonth!=3
                set @mid=@mid+1
    END
else
    begin
        if @isSC=1
            if @mMonth!=3
                set @mid=@mid-1
    end

if @mDay>@mid
    begin
        set @sDay=@mDay-@mid;
        set @sMonth=@sMonth+1;
    end
else
    begin
        if @sMonth<7
            set @sDay=31+(@mDay-@mid);
        else
            begin
                if @sMonth=12
                    BEGIN
                        if @isSC=1
                            set @sDay=30+(@mDay-@mid); 
                        else
                            set @sDay=29+(@mDay-@mid); 
                    END
                else
                    set @sDay=30+(@mDay-@mid);
            end
    end



return Cast(@sYear as nvarchar)+'/'+Cast(@sMonth as nvarchar)+'/'+Cast(@sDay as nvarchar)
end
© www.soinside.com 2019 - 2024. All rights reserved.