简体   繁体   English

SQL 服务器日期时间转换问题

[英]SQL Server datetime conversion Problem

I need to insert a datetime value into datetime column in SQL Server 2005我需要在 SQL Server 2005 的datetime时间列中插入一个datetime时间值

I am passing DateTime variable from the.aspx page我从 .aspx 页面传递DateTime变量

Which needs to be inserted in the column.需要将其插入列中。

Example:例子:

Table(date datetime)

@sql = 'insert into Table (date) values('+@datetime+')'
exec(@sql)

getting conversion failed message.收到转换失败消息。

Any idea how to do this.任何想法如何做到这一点。

Very Urgent.很紧急。

Thanks.谢谢。

Add escaped single quotes around the datetime value.在日期时间值周围添加转义的单引号。 Normally they are passed as strings.通常它们作为字符串传递。

See if this works:看看这是否有效:

@sql = 'insert into Table (date) values('''+@datetime+''')'
exec(@sql)

You need string delimiters - in T-SQL this is doubled-up single quotes.您需要字符串分隔符——在 T-SQL 中,这是双引号。

SET @sql = 'insert into Table (date) values('''+@datetime+''')'
exec(@sql)

However it still might fail, depending on the format of the string.但是它仍然可能会失败,具体取决于字符串的格式。 Any reason you're building a SQL string, prone to SQL injection, instead of just saying:您构建 SQL 字符串的任何原因,容易发生 SQL 注入,而不仅仅是说:

INSERT Table(date) SELECT @datetime;

? ?

Make sure your query/stored procedure are expecting to receive the parameter as a datetime variable (not varchar(20) , or anything else like that), and make sure your ASP.Net code is passing the value as a datetime value also.确保您的查询/存储过程期望将参数作为datetime时间变量(不是varchar(20)或其他类似的)接收,并确保您的 ASP.Net 代码也将值作为datetime时间值传递。

Basically, for best datetime handling, convert them from strings into datetimes as early as possible when accepting them as input (eg convert them in an appropriate event in your code behind in ASP.NET), keep them as datetimes whenever passing them to/from the database, and fromat them back as strings as late as possible when outputting them (eg in view code for asp.net mvc, or when assigning to the Text property of an ASP.Net control)基本上,为了获得最佳的日期时间处理,在接受它们作为输入时尽早将它们从字符串转换为日期时间(例如,在 ASP.NET 后面的代码中将它们转换为适当的事件),将它们作为日期时间传递给/从数据库,并在输出它们时尽可能晚地将它们作为字符串返回(例如,在 asp.net mvc 的视图代码中,或在分配给 ASP.Net 控件的 Text 属性时)

Try making this small change to your sql statement尝试对您的 sql 语句进行这个小改动

@sql = "insert into Table (date) values ('"+ @datetime + "')"

Besides the other suggestions with delimiters and parenthesis mismatches, Date is a reserved keyword, use [Date] instead.除了分隔符和括号不匹配的其他建议外,Date 是保留关键字,请改用 [Date]。

Declare @datetime datetime
Set @datetime=GetDate()

Declare @sql nvarchar(1000)
Declare @param nvarchar(1000)
Set @param='@datetime datetime'

SET @sql = 'insert into Table (date) values(@datetime)'

exec sp_executesql @sql,@param,@datetime

you have to learn the sql injection for dynamic queries.您必须学习用于动态查询的 sql 注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM