简体   繁体   中英

Convert code in MS Access to SQL server

The following two functions, I would like to convert them from Access into SQL server, how can I moddify my code? Thank you so much. I never use SQL server before, and trying to learn it hard. LIS is a drive

Public Function PathDate(Ndate As Date) As Long
    PathDate = (Year(Ndate) * 10000) + (Month(Ndate) * 100) + Day(Ndate)
End Function

Public Function NormalDate(LISDate As Long) As Date

    If (LISDate = -1) Then
        NormalDate = "-1"
    Else
        NormalDate = MonthName(LISDate \ 100 Mod 100) & " " & LISDate Mod 100 & " ," & LISDate \ 10000
    End If
End Function

In SQL Server, you don't have to do all that math to convert dates to ints and back.

First one:

CREATE FUNCTION dbo.PathDate
(
    @NDate DATETIME
)
RETURNS INT
AS
BEGIN
    RETURN (SELECT CONVERT(CHAR(8), @NDate, 112));
END
GO

Second one:

CREATE FUNCTION dbo.NormalDate
(
    @LISDate INT
)
RETURNS VARCHAR(32)
AS
BEGIN
    RETURN (SELECT DATENAME(MONTH, d) 
      + ' ' + RTRIM(DAY(d)) 
      + ', ' + RTRIM(YEAR(d)) 
    FROM 
    (
      SELECT d = CONVERT(DATETIME, CONVERT(CHAR(8), @LISDate))
    ) AS d);
END
GO

Example usage:

DECLARE @NDate DATETIME, @LISDate INT;

SELECT @NDate = GETDATE(), @LISDate = 20120523;

SELECT dbo.PathDate(@NDate), dbo.NormalDate(@LISDate);

Results:

20120523        May 23, 2012

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM