参数化查询被截断,参数丢失

时间:2012-05-29 13:31:28

标签: c# sql-server ado.net sqlparameters executescalar

我有一段代码:

command.Parameters.Clear();
command.Parameters.Add(ownerUserIDParam);
command.Parameters.Add(buddyUserIDParam);
command.Parameters.Add(timestampParam);
command.Parameters.Add(new SqlParameter("@GiftID", giftID));
command.Parameters.Add(new SqlParameter("@GiftStatus", (byte)GiftStatusEnum.wait));
command.CommandText = "INSERT INTO SentGefts (OwnerUserID, BuddyUserID, CreateTS, GiftID, Status, AcceptRejectTS, ParentEntityType, ParentEntityID) VALUES (@OwnerUserID, @BuddyUserID, @TS, @GiftID, @GiftStatus, @TS, 0 ,0);";
command.CommandText += "SELECT @@IDENTITY;";
result.GiftInstanceID = long.Parse(command.ExecuteScalar().ToString());

我接受:参数化查询'(@ OwnerUserID int,@ BuddyUserID int,@ TS datetime,@ GiftID int,@ Gif'需要参数' @ GiftStatus',没有提供。

注意:'(@ OwnerUserID int,@ BuddyUserID int,@ TS datetime,@ GiftID int,@ Gif'被截断,正好是64个符号......它只是以未完成的参数名称结束' Gif'(例外也与此参数有关。)

为什么它看不到我的参数?

UPD: 如果我以这种方式重新添加最后一个参数(@GiftStatus):     command.Parameters.AddWithValue(" @ GiftStatus",(byte)GiftStatusEnum.wait);

这样事情就开始起作用了。但我无法弄清楚.Add(new SqlParamter());

的错误。

2 个答案:

答案 0 :(得分:3)

您需要提供所有参数及其名称 你最好使用Paramteres.AddWithValue(...)。 所以:

Parameters.AddWithValue("@OwnerUserID", ...);
Parameters.AddWithValue("@BuddyUserID", ...);
Parameters.AddWithValue("@TS", ...);
Parameters.AddWithValue("@GiftID", ...);
Parameters.AddWithValue("@GiftStatus", ...);

答案 1 :(得分:1)

我认为您在ExecuteScalar()

之前缺少以下命令
command.CommandText += "SELECT @@IDENTITY;";
command.CommandType = CommandType.Text;
result.GiftInstanceID = long.Parse(command.ExecuteScalar().ToString());