简体   繁体   English

如何使用存储过程将datetime插入SQL Server数据库表中?

[英]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.

相关问题 如何在存储过程中读取xml文件并将其插入到SQL Server中的表中 - How to read xml file in stored procedure and insert it in table in sql server 如何将 sql 服务器存储过程数据插入到新表中? - how can insert sql server stored procedure data to the new table? 具有多个表插入的SQL Server存储过程 - SQL Server stored procedure with multiple table insert SQL Server 存储过程。 插入表 - SQL Server stored procedure. insert into table 使用存储过程将记录从用户定义的表类型插入SQL Server数据库 - Insert records into SQL Server database from user defined table type using stored procedure SQL 插入表存储过程 - SQL Insert into table stored procedure 如何使用存储过程在SQL Server中透视表? - How to pivot table in SQL Server with a stored procedure? 如何比较两个表的列并根据SQL Server中存储过程的比较将值插入新表中 - How to compare column of two table and insert a value into new table based on comparison in stored procedure in SQL Server 如何比较两个表列并将其插入到SQL Server中的新表存储过程中 - How to compare two table columns and insert it into new table stored procedure in SQL Server 如何使用存储过程 SQL Server 从表中复制记录并插入到同一个表中 - How to copy records from table and insert into same table using stored procedure SQL Server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM