簡體   English   中英

如何基於星期幾過濾數據庫中的數據?

[英]How To Filter Data in Database Based on Day of Week?

我的數據庫中有一列,該列在不同工作日為我的聯系人保存一個字符串。

例如:聯系人1在星期一和星期三工作。

因此,在Week_Day列中,聯系人1的字符串為“星期一,星期三”。 我試圖只顯示在一周的當前日期工作的行,下面的代碼。 我嘗試使用IN子句,但是它不起作用,因為我沒有要過濾的星期幾。 救命!

string today = DateTime.Today.ToString("MM-dd-yy");

string day = DateTime.Today.DayOfWeek.ToString();
string find = "select convert(varchar(8), start, 10) AS start, convert(varchar(8), end_date, 10) AS end_date, ContactName, DepartmentName, Hours, Phone, Week_Day from Schedule join Contacts on Schedule.ContactId = Contacts.ContactId inner join Departments on Contacts.DepartmentId = Departments.DepartmentId where @Current BETWEEN start AND end_date AND Week_Day IN (@Day)";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("@Current", SqlDbType.Date).Value = today;
comm.Parameters.Add("@Day", SqlDbType.NVarChar).Value = day;

con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds);
GridView3.DataSource = ds;
GridView3.DataBind();

con.Close();

好吧,您可以像這樣獲得星期幾(名稱):

string day = DateTime.Today.ToString("dddd");

然后,您可以在WHERE查詢中使用LIKE來使用它。 將查詢更改為:

WHERE Week_Day LIKE @day

並為您添加@day參數,以在開始和結束時包含%

comm.Parameters.Add("@Day", SqlDbType.NVarChar).Value = "%" + day + "%";

更多有關LIKE的信息在這里


注意:正如一些評論所提到的,最好不要以這種方式將數據存儲在單個字符串列中,但是我已經根據您的問題回答了。

也許與DateName()和CharIndex()

Where CHARINDEX(DateName(WEEKDAY,GetDate()),Week_Day)>0 and...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM