我的sql表包含许多人的出生日期。日期为mm / dd / yyyy格式。我想选择下一个30天出生日的人员详细信息。我使用以下查询,
SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE
ltrim(str(year(GETDATE()))) + -' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND
ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' +
ltrim(str(day(Mem_DOB))) <= getdate() + 30
完整代码是
public List<MemberData> GetThisMonthBirthday()
{
List<MemberData> MD = new List<MemberData>();
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Mem_FirstNA, Mem_LastNA, Mem_DOB FROM MemberDetails WHERE ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) >= getdate() - 1 AND ltrim(str(year(GETDATE()))) + '-' + ltrim(str(month(Mem_DOB))) + '-' + ltrim(str(day(Mem_DOB))) <= getdate() + 30", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberData mb = new MemberData();
mb.Mem_NA = (string)reader["Mem_FirstNA"];
mb.Mem_LastNA =(string)reader["Mem_LastNA"];
mb.Mem_DOB = (Convert.ToDateTime(reader["Mem_DOB"]));
MD.Add(mb);
}
}
catch (Exception e) { throw e; }
finally { if (con.State == System.Data.ConnectionState.Open) con.Close(); }
return MD;
}
}
问题是这个检查只到12月31日,如果在01/01/1987的人生日,查询没有选择那个细节。请帮我解决这个问题。谢谢
答案 0 :(得分:1)
有很多方法可以做到这一点,你需要条件逻辑取决于你是否在年底的30天内。如果您正在使用SQL Server,我会将逻辑包装在函数中以使其更具可读性,例如:
CREATE FUNCTION [dbo].[IsBirthdayInRange]
(
@Birthday DATETIME,
@StartDate DATETIME,
@EndDate DATETIME
)
RETURNS BIT
AS
BEGIN
DECLARE @StartMonthDay INT
DECLARE @EndMonthDay INT
DECLARE @BirthdayMonthDay INT
SET @StartMonthDay = MONTH(@StartDate) * 100 + DAY(@StartDate)
SET @EndMonthDay = MONTH(@EndDate) * 100 + DAY(@EndDate)
SET @BirthdayMonthDay = MONTH(@Birthday) * 100 + DAY(@Birthday)
IF YEAR(@StartDate) <> YEAR(@EndDate)
BEGIN
IF @BirthdayMonthDay >= @StartMonthDay OR @BirthdayMonthDay <= @EndMonthDay
BEGIN
RETURN 1
END
END
ELSE
BEGIN
IF @BirthdayMonthDay >= @StartMonthDay AND @BirthdayMonthDay <= @EndMonthDay
BEGIN
RETURN 1
END
END
RETURN 0
END
然后您可以将其用作:
...
WHERE IsBirthdayInRange(Mem_DOB, GETDATE(), GETDATE() + 30)