SQL Server datetime conversion Problem
I need to insert a datetime
value into datetime
column in SQL Server 2005
I am passing D开发者_如何学运维ateTime
variable from the .aspx page
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.
You need string delimiters - in T-SQL this is doubled-up single quotes.
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:
INSERT Table(date) SELECT @datetime;
?
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)
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.
Basically, for best datetime handling, convert them from strings into datetimes as early as possible when accepting them as input (e.g. 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 (e.g. in view code for asp.net mvc, or when assigning to the Text property of an ASP.Net control)
Besides the other suggestions with delimiters and parenthesis mismatches, Date is a reserved keyword, use [Date] instead.
Try making this small change to your sql statement
@sql = "insert into Table (date) values ('"+ @datetime + "')"
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.
精彩评论