SQL检查日期是否是从上个月开始的N天

时间:2016-12-11 19:29:06

标签: sql sql-server date

我需要根据dateIssued检查发票的编辑(在表格中说出发票)。

(SQL Server 2008 R2)

这个想法是,上个月的发票数据可以更改,直到当月的第N天。之后,只能更改当前月份的发票。 Invoices绝不会在2个月后再改变。

实施例。可以说N = 20天

这意味着我可以将11月份的发票更改为12月20日。 12月21日我只能改变12月的发票。

我希望我足够描述:(

SELECT invoiceNo, dateIssued FROM Invoices;

invoiceNo dateIssued
001       2016-10-30 00:00:00.000
002       2016-12-01 00:00:00.000
003       2016-11-03 00:00:00.000
004       2016-11-24 00:00:00.000
005       2016-09-09 00:00:00.000

我无法构建一个优雅的算法,可以从表中选择正确的编辑发票,具体取决于系统的日期。

感谢名单

3 个答案:

答案 0 :(得分:2)

如果您想获得今天可以修改的发票,那么就像这样:

select i.*
from invoices i
where year(dateissued) * 12 + month(dateissued) = year(getdate()) * 12 + month(getdate()) or
      (day(getdate()) <= @n and
       year(dateissued) * 12 + month(dateissued) = year(getdate()) * 12 + month(getdate()) - 1
      ) ;

使用年* 12 +月的时髦表达只是获得自零时起的月数。现在和上个月都很方便。

答案 1 :(得分:0)

Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click

    For Each file As String In System.IO.Directory.GetFiles(dir)
        FfilesComboBox.DisplayMember = "key"
        FfilesComboBox.ValueMember = "value"
        FfilesComboBox.Items.Add(New DictionaryEntry(System.IO.Path.GetFileNameWithoutExtension(file), System.IO.Path.GetFileName(file)))
    Next

End Sub

Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
    Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.Value.ToString)
    'start the process using the openfile string
    Process.Start(openfile)
End Sub

答案 2 :(得分:0)

DECLARE @LastDayForEditingPreviousMonth INT = 20

-- Return only invoices for the current month, of those for last month if the @LastDayForEditingPreviousMonth day has not been passed
SELECT *
FROM invoices
WHERE (     DATEPART(YEAR,dateissued) = DATEPART(YEAR,GETDATE()) 
        AND DATEPART(MONTH,dateissued) = DATEPART(MONTH,GETDATE())
      ) -- Invoices for this month
OR (    DATEPART(DAY,GETDATE()) <= @LastDayForEditingPreviousMonth
    AND DATEPART(YEAR,dateissued) = DATEPART(YEAR,GETDATE())
    AND DATEPART(MONTH,dateissued) = DATEPART(MONTH,GETDATE()) - 1
) -- Invoices from last month (if eligible)