如何将日,月和年转换为月和年 [英] How to convert day, month and year into month and year
问题描述
大家好
我的数据库上有一个名为MCALLERS的表,其中有一个名为CallDate的列,数据类型是datetime存储的数据,如2016-02-01 17:01 :00.000
我的网页表格我有下拉列表,其中包含2016年3月的月份和年份。
如何将日期时间转换为我搜索数据的月份和年份。我想使用月份和年份(2016年3月)从数据库中搜索数据。我在唱C#。
提前致谢
我的尝试:
Hi Everyone
I have table called MCALLERS on my database that has column which called CallDate, datatype is datetime stored data as 2016-02-01 17:01:00.000
on my web Form I have dropdownlist which is populating month and year as March-2016.
how to convert datetime into month and year when I search data.I want to search data from database using Month and year as (March-2016). I'm sing C#.
Thanks in advance
What I have tried:
select BusinessCallYN,CallID,NewNam,CallDate,CalledNo,CallExt,CallDuration,Amount,tmpNewNam from MCALLERS where UserName='"+txtEmail+"' and CallDate>='"+cmddropdownlist1+"' and CallDate<'"+cmddropdownlist1+"' and Amount>0 order by CallDate
错误消息:转换失败从字符串转换日期和/或时间时。
Error message : Conversion failed when converting date and/or time from character string.
推荐答案
你可以使用month和yesr来搜索那些部分
You can use month and yesr to search on just those parts
where month(CallDate) = 3 and year(CallDate) = 2016
但是你应该使用参数化查询而不是字符串连接,因为你的代码是容易受到SQL注入攻击。
However you should use parameterised queries rather than string concatenation as your code is liable to sql injection attacks.
您需要查看SQL Server CONVERT()函数 [ ^ ]了解DateTime转换。
希望上面的链接可以帮到你。
Hi,
You need to review SQL Server CONVERT() Function[^] to understand the DateTime conversion.
Hope above link will help you.
对于初学者,不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。
其次,请尝试:
For starters, 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.
Secondly, try:
SELECT * FROM MyTable WHERE DATEPART(year, DateColumn) = yearYouWant AND DATEPART(month, DaetColumm) = monthYouWant
如果你想直接使用你的组合框,那么你需要确定组合框包含的确切数据类型,因为字符串和DateTime将需要不同的解决方案。
If you want to use your combobox directly, then you need to identify exactly what datatype the combobox contains, because string and DateTime will require different solutions.
这篇关于如何将日,月和年转换为月和年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!