简体   繁体   中英

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
Incorrect syntax near '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() . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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