且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何仅在当前月份获取id的计数。

更新时间:2023-01-27 23:40:25

首先,不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

然后试试这个:

 conn.Open(); 
SqlCommand se = new SqlCommand( select从daily_att计算(empid),其中empid = @ ID AND myDateColumneName> DATEADD(day, - DATEPART(day,GETDATE()),GETDATE()),conn);
se.Parameters.AddWithValue( @ ID,txt_empid.Text);
string recid = se.ExecuteScalar()。ToString();
lbl_nofday.Text = recid;
conn.Close();

虽然我个人认为,我会将其作为存储过程,并使用变量来存储GETDATE结果,以防止在月末出现间歇性错误。


hi , everyone:
now i am make an application for attendance maintenance,in this application i would calculate no of days presented an id in the particular month, how can i use the query, i am using below to calculate no of day presented in a month.how can i fetch for a particular month?
my code is here

conn.Open();
           SqlCommand se = new SqlCommand("select count(empid) from daily_att where empid=''"+txt_empid.Text+"''", conn);
           string recid = se.ExecuteScalar().ToString();
           lbl_nofday.Text = recid;
           conn.Close();

Firstly, do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
Then try this:
conn.Open();
SqlCommand se = new SqlCommand("select count(empid) from daily_att where empid=@ID AND myDateColumneName > DATEADD(day, - DATEPART(day, GETDATE()), GETDATE())", conn);
se.Parameters.AddWithValue("@ID", txt_empid.Text);
string recid = se.ExecuteScalar().ToString();
lbl_nofday.Text = recid;
conn.Close();

Although personally, I would make this a stored procedure, and use a variable to store the GETDATE result to prevent intermittent errors at the end of the month.