[英]How to insert datetime into a SQL Server database table with a stored procedure?
I've created the following stored procedure: 我创建了以下存储过程:
create proc sp
@Tablename nvarchar(max), @Dt datetime
as
begin
exec('insert '+@Tablename+' values('+@Dt+')')
end
When I execute that stored procedure 当我执行该存储过程时
exec sp 'TbName','2012-12-10 13:38:00.000'
I got this error : 我收到此错误:
Msg 102, Level 15, State 1, Line 1 Msg 102,第15级,状态1,第1行
Incorrect syntax near '10'. '10'附近的语法不正确。
Thanks in advance for any help. 在此先感谢您的帮助。
You need to put quotes around the date value. 您需要在日期值两边加上引号。 Otherwise it is interpreted as numbers and other things: 否则,它将被解释为数字和其他内容:
create proc sp
@Tablename nvarchar(max), @Dt datetime
as
begin
exec('insert '+@Tablename+' values(''+@Dt+'')')
end;
When writing such code, it is good practice to put separate the variable substitution from the exec()
. 编写此类代码时,最好将变量替换与exec()
分开。 That way you can easily print out the string: 这样,您可以轻松地打印出字符串:
create proc sp
@Tablename nvarchar(max), @Dt datetime
as
begin
declare @sql nvarchar(max);
set @sql = 'insert '+@Tablename+' values(''+@Dt+'')';
exec(@sql);
end;
If you had printed out what you were executing, you might have spotted the problem right away. 如果您已打印出正在执行的内容,则可能会立即发现该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.