我想使用.net / C#来开发Web应用程序。我有一个SQL Server存储过程,我想传递动态日期时间参数。
当我在exec(@sql)
使用时,这里是带有参数I的存储过程:
错误信息:System.Data.SqlClient.SqlException:
从字符串转换datetime时转换失败。
我甚至尝试传递一些实际值(见下文),并尝试在SQL Server中进行调试,但它不起作用。
任何人都可以帮助我吗?非常感谢。
ALTER PROCEDURE [dbo].[production_tb_WorkshopDailyReports_INSERT]
@intDepartmentID int,
@intReportUserID int,
@intProductionLineID int,
@intBatchID int,
@intVINID int,
@columnname nvarchar(255),
@dtOnlineTime datetime,
@strRemark nvarchar(50),
@intCreateUserID int
AS
BEGIN
declare @column nvarchar(255)
declare @sql nvarchar(1000)
declare @intID int
set @columnname = 'dtOnlineTimeChassis'
set @column = @columnname
set @intDepartmentID = 1
set @intReportUserID = 1
set @intProductionLineID = 1
set @intBatchID = 1
set @intVINID = 1
set @dtOnlineTime = '2016-04-26 10:00:00pm'
set @strRemark = 'remark information'
set @intCreateUserID = 1
set @sql = 'Insert Into production_tb_WorkshopDailyReports (intDepartmentID, intReportUserID, intProductionLineID, intBatchID, intVINID,' + @column + ', strRemark, intCreateUserID) values ' + '(' + cast(@intDepartmentID as nvarchar(20)) + ',' + cast(@intReportUserID as nvarchar(20)) + ',' + cast(@intProductionLineID as nvarchar(20)) + ',' + cast(@intBatchID as nvarchar(20)) + ',' + cast(@intVINID as nvarchar(20)) + ',' + @dtOnlineTime + ',' + @strRemark + ',' + cast(@intCreateUserID as nvarchar(20)) + ')'
(@intReportUserID as nvarchar(20))+','+cast(@intProductionLineID as nvarchar(20))+','+cast(@intBatchID as nvarchar(20))+','+cast(@intVINID as nvarchar(20))+','+''+','+cast(@intCreateUserID as nvarchar(20))+')'
exec(@sql)
End
答案 0 :(得分:0)
+ ',''' + convert(varchar(26), @dtOnlineTime, 121) + ''',''' + @strRemark + ''',' +
答案 1 :(得分:0)
我想这一切:
set @columnname = 'dtOnlineTimeChassis'
set @column = @columnname
set @intDepartmentID = 1
set @intReportUserID = 1
set @intProductionLineID = 1
set @intBatchID = 1
set @intVINID = 1
set @dtOnlineTime = '2016-04-26 10:00:00pm'
set @strRemark = 'remark information'
set @intCreateUserID = 1
仅用于测试SP,其他时间@columnname
变量中会有不同的内容。如果此语句为false,那么我建议使用简单的INSERT
而不是动态SQL。
首先更改此信息:
',' + @dtOnlineTime + ',' + @strRemark + ','
对此:
',''' + CONVERT(nvarchar(50),@dtOnlineTime,120)+''',''' + @strRemark + ''','
我建议使用120
日期样式(ODBC规范yyyy-mm-dd hh:mi:ss(24h)
,有关更多信息,请阅读MSDN),并且必须将datetime变量和变量与一些注释放入''
。
第二次删除或评论此部分(set @sql = ...
之后的下一个字符串):
(@intReportUserID as nvarchar(20))+','+cast(@intProductionLineID as nvarchar(20))+','+cast(@intBatchID as nvarchar(20))+','+cast(@intVINID as nvarchar(20))+','+''+','+cast(@intCreateUserID as nvarchar(20))+')'
在PRINT
查询后,您会看到以下内容:
Insert Into production_tb_WorkshopDailyReports (intDepartmentID, intReportUserID, intProductionLineID, intBatchID, intVINID,dtOnlineTimeChassis, strRemark, intCreateUserID) values
(1,1,1,1,1,'2016-04-26 22:00:00','remark information',1)
尝试执行它。