简体   繁体   中英

How can I calculate the next birthday by computed column in ssql

i would want to calculate the next birthday of people in my database i have a column called dateofbirth and other called birthday i want to be able to compute the birthday using a computed column in ssql.

(datepart(year,getdate())&datepart(day,[DateofBirth]))

i thaught i could do this pragmatically by datatable but i get an error. below is my code.

Dim birthda As New SqlDataAdapter(birthcmd)

    Dim birthdt As New DataTable
    birthda.Fill(birthdt)

    For Each rw As DataRow In birthdt.Rows
        Dim dob As String = rw.Item(3)



        Dim mdat As Date = FormatDateTime(dob, DateFormat.ShortDate)

        Dim bday As Date = (Date.Today.Year & mdat.Month & mdat.Day)


        Dim yers As Integer = DateDiff(DateInterval.Year, mdat.Date, Today.Date)
        Dim moths As Integer = DateDiff(DateInterval.Month, mdat.Date, Today.Date)
        Dim dys As Integer = DateDiff(DateInterval.Day, mdat.Date, Today.Date)

Please try this for your command:

    birthcmd.CommandText = "SELECT        DateofBirth, " & _
                      "DATEADD(year, DATEDIFF(year, DateofBirth, { fn NOW() }) + (CASE WHEN month(dateofbirth) * 100 + day(dateofbirth) < month({ fn NOW() }) * 100 + day({ fn NOW() }) THEN 1 ELSE 0 END), DateofBirth) AS Nextbday, " & _
                      "DATEDIFF(year, { fn NOW() }, DATEADD(year, DATEDIFF(year, DateofBirth, { fn NOW() }) + (CASE WHEN month(dateofbirth) * 100 + day(dateofbirth) < month({ fn NOW() }) * 100 + day({ fn NOW() }) THEN 1 ELSE 0 END), DateofBirth)) AS Diffyers, " & _
                      "DATEDIFF(month, { fn NOW() }, DATEADD(year, DATEDIFF(year, DateofBirth, { fn NOW() }) + (CASE WHEN month(dateofbirth) * 100 + day(dateofbirth) < month({ fn NOW() }) * 100 + day({ fn NOW() }) THEN 1 ELSE 0 END), DateofBirth)) AS Diffmoths, " & _
                      "DATEDIFF(day, { fn NOW() }, DATEADD(year, DATEDIFF(year, DateofBirth, { fn NOW() }) + (CASE WHEN month(dateofbirth) * 100 + day(dateofbirth) < month({ fn NOW() }) * 100 + day({ fn NOW() }) THEN 1 ELSE 0 END), DateofBirth)) AS Diffdys " & _
                      "FROM myBirthdayTable"

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