插入数据库c#时出错,数据转换失败

时间:2013-07-30 18:51:22

标签: c# sql database insert

尝试在我的表中执行insert语句时,出现此错误:

  

数据转换失败。 [OLE DB状态值(如果已知)= 2]

我在网上完成了我的研究,似乎无法找到解决这个问题的答案。

insert语句如下所示:

INSERT INTO [Beverages] (BeverageID, ParentBeverageID, Name, PreferredRecipeVersion, 
                         SpecificCustomerID, AcceptabilityRating, ShowBeverage, Availability, 
                         Family, EngagedPriority, SmilePriority, Collections) 
VALUES (1475614, 1475633, 'Caffeine-free', 3, 1, 0, 1, 1, 'A', 'NULL', 1, 'UK')

我最初构建的表(确实创建了它)如下所示:

string beverages = "CREATE TABLE [Beverages]([BeverageID] INT NOT NULL,[ParentBeverageID] INT, [Name] NVARCHAR(40) NOT NULL,[PreferredRecipeVersion] INT NOT NULL DEFAULT(1),[SpecificCustomerID] INT NOT NULL DEFAULT(0),[AcceptabilityRating] INT NOT NULL DEFAULT(0),[ShowBeverage] INT NOT NULL DEFAULT(1),[Availability] INT NOT NULL DEFAULT(1),[Family] NVARCHAR(1),[EngagedPriority] INT,[SmilePriority] INT NOT NULL DEFAULT(0), [Collections] NVARCHAR(50) NOT NULL);";
string beverages1 = "ALTER TABLE [Beverages] ADD CONSTRAINT [PK__Beverages__000000000000134A] PRIMARY KEY ([BeverageID]);";
string beverages2 = "CREATE INDEX [PK_BeverageID] ON [Beverages] ([BeverageID] ASC);";
db.ExecuteSqlCommand(beverages, null, __gulfstreamDataConn);
db.ExecuteSqlCommand(beverages1, null, __gulfstreamDataConn);
db.ExecuteSqlCommand(beverages2, null, __gulfstreamDataConn);

我不知道会导致这个问题的原因,但感谢您提前提供的帮助!

3 个答案:

答案 0 :(得分:2)

如果要将字段 EngagedPriority 设置为NULL,则应该在没有单引号的情况下写入NULL。使用单词NULL周围的引号会使解析器将值识别为字符串,但字段 EngagedPriority 是Int ....

 string beverages = "CREATE TABLE [Beverages]([BeverageID] INT NOT NULL," + 
                    "[ParentBeverageID] INT, [Name] NVARCHAR(40) NOT NULL," + 
                    "[PreferredRecipeVersion] INT NOT NULL DEFAULT(1)," + 
                    "[SpecificCustomerID] INT NOT NULL DEFAULT(0)," + 
                    "[AcceptabilityRating] INT NOT NULL DEFAULT(0)," + 
                    "[ShowBeverage] INT NOT NULL DEFAULT(1)," + 
                    "[Availability] INT NOT NULL DEFAULT(1)," + 
                    "[Family] NVARCHAR(1)," + 
                -->>"[EngagedPriority] INT," + 
                    "[SmilePriority] INT NOT NULL DEFAULT(0), " + 
                    "[Collections] NVARCHAR(50) NOT NULL);";


  "INSERT INTO [Beverages] (BeverageID, ParentBeverageID, Name, PreferredRecipeVersion," + 
  "SpecificCustomerID, AcceptabilityRating, ShowBeverage, Availability, Family," +
  "EngagedPriority, SmilePriority, Collections) " + 
  "Values (1475614,1475633,'Caffeine-free ',3,1,0,1,1,'A',NULL,1,'UK')
                                                          ^^^^

答案 1 :(得分:0)

Null为NULL而非'NULL' - 从INSERT中删除单引号。

答案 2 :(得分:0)

您的问题是您正在插入'NULL'而不是NULL。当您使用'NULL'时,SQL将其作为VarChar。 NULL(无引号)将为您提供所需的答案。