【问题标题】:Error: Cannot insert the value NULL into column错误:无法将值 NULL 插入列
【发布时间】:2014-03-19 19:46:50
【问题描述】:

我有一个绑定到 sqldatasource 的 gridview。正在尝试运行更新存储过程。

我不断收到此错误...

Cannot insert the value NULL into column 'MyFKId', table 'dbo.MyTable'; 
column does not allow nulls. INSERT fails. The statement has been 
terminated. 

我知道答案似乎很明显,即我试图将 null 插入不允许的列中。问题是我知道我正在为“MyFKId”赋值。在我的代码中,我设置了一个断点,并在此行运行后看到了一个值...

dsMyDataSource.UpdateParameters.Item("MyFKId").DefaultValue = SomeId

SomeId 确实有一个值。它不为空。你认为可能有什么问题? SQLDataSource 设置如下...

 <asp:SqlDataSource ID="dsMyDataSource" runat="server" ConnectionString="xxxxx"
    SelectCommand="xxxxx" SelectCommandType="StoredProcedure"  
    UpdateCommandType="Text"  
    UpdateCommand=" Execute s_MyStoredProc @MyFKId,...@UserId">
      <UpdateParameters>
             <asp:Parameter Name="MyFKId" Type="Int32" />
              ...
      </UpdateParameters>
 </asp:SqlDataSource>

【问题讨论】:

  • 您还需要将代码发布到s_MyStoredProc 以获得合理的答案。
  • 当我设置断点时,我确实看到 defaultvalue 从 SomeId 变量中获取了一个值。之后没有代码可以调整它。我还应该在哪里检查?
  • 参数是 SQL Server 看到的,而不是您认为 SQL Server 应该看到的。显然,两者之间是有区别的。
  • 我认为你必须展示存储过程。确保参数MyFKId 是您在存储过程中所期望的。
  • 异常消息显示 INSERT fails。也许您需要设置InsertParameters 属性。

标签: asp.net vb.net gridview ado.net


【解决方案1】:

不要使用EXECUTE 来调用您的存储过程。使用InsertCommand

 <asp:SqlDataSource ID="dsMyDataSource" runat="server" ConnectionString="xxxxx"
    InsertCommand="s_MyStoredProc" InsertCommandType="StoredProcedure">
      <InsertParameters>
             <asp:Parameter Name="MyFKId" Type="Int32" />
              ...
      </InsertParameters>
 </asp:SqlDataSource>

并使用InsertParameters设置参数。

dsMyDataSource.InsertParameters("MyFKId").DefaultValue = SomeId

无法尝试,但希望能为您解决。

【讨论】:

  • 存储过程实际上会执行 INSERTS 和 UPDATES,具体取决于某些变量和逻辑。但从技术上讲,在这种情况下,它作为更新查询/命令工作。
  • 您应该使用 InsertCommand 的原因与您的存储过程的真正作用无关,它是为了正确地为参数分配值。 InsertCommand 确保它不会期望来自该查询的结果。根本没有 UpdateCommandType="StoredProcedure" 所以你必须使用 InsertCommand 来执行存储过程。它应该适用于任何不返回查询结果的存储过程。试试我的建议吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多