我正在使用 SQL Server 存储过程通过 C# 将数据放入数据库。当我从 SQL Server Management Studio 中运行存储过程时,它可以工作,但是当我尝试使用 C# 插入行时,它失败了,我无法找出原因。最初我在使用存储过程中的类型时遇到了麻烦,DATETIME
但现在当我使用 CAST 时它可以工作。我也尝试过将DateTime
值作为字符串从 C# 传递,但这也不起作用!?
我的SP如下:
ALTER PROCEDURE [dbo].[SaveFlightInfo]
(
@FlightInfoID int,
@AirportFrom varchar(5),
@AirportTo varchar(5),
@TimeDeparture datetime,
@TimeArrival datetime,
@Price float,
@DateAdded datetime,
@Carrier varchar(30),
@Url varchar(300)
)
AS
DECLARE @sql as varchar(1000)
--If the primary key is zero then insert new record
IF ( @FlightInfoID = 0) BEGIN
DECLARE @sql3 as varchar(1000)
SET @sql ='
INSERT INTO '+@AirportFrom+'
(AirportFrom,
AirportTo,
TimeDeparture,
TimeArrival,
Price,
DateAdded,
Carrier,
Url)
VALUES ('''+@AirportFrom+''',
'''+@AirportTo+''',
CAST('''+CAST(@TimeDeparture as varchar(50))+''' as DATETIME),
CAST('''+CAST(@TimeArrival as varchar(50))+''' as DATETIME),
CAST('''+CAST(@Price as varchar(10))+''' as FLOAT),
CAST('''+CAST(@DateAdded as varchar(50))+''' as DATETIME),
'''+@Carrier+''',
'''+@Url+''')
'
END
EXEC(@sql)
我的 C# 代码如下:
Database db = DatabaseFactory.CreateDatabase("DBConnectionString");
DbCommand dbCommand = db.GetStoredProcCommand("SaveFlightInfo");
db.AddInParameter(dbCommand, "FlightInfoID", DbType.Int32, flightInfoID);
db.AddInParameter(dbCommand, "AirportFrom", DbType.String, airportFrom);
db.AddInParameter(dbCommand, "AirportTo", DbType.String, airportTo);
db.AddInParameter(dbCommand, "TimeDeparture", DbType.DateTime, timeDeparture);
db.AddInParameter(dbCommand, "TimeArrival", DbType.DateTime, timeArrival);
db.AddInParameter(dbCommand, "Price", DbType.Int16, price);
db.AddInParameter(dbCommand, "DateAdded", DbType.DateTime, dateAdded);
db.AddInParameter(dbCommand, "Carrier", DbType.String, carrier);
db.AddInParameter(dbCommand, "Url", DbType.String, url);
IDataReader dr = db.ExecuteReader(dbCommand);