从存储过程中检索数据

时间:2017-07-11 19:58:08

标签: sql-server vb.net stored-procedures

我的存储过程调用似乎遇到了麻烦。我试图从存储过程中获取所有信息,该存储过程将单个列返回到数据表中。我已经在这里找到了大多数解决方案,似乎无法弄清楚它为什么不起作用。我的数据表有一个主键约束,因为它有多个值。但是,根据我的阅读,这是不必要的,因为Fill上的SqlDataAdapter只会合并这些更改?

到目前为止,这是我的代码:

Dim dtValues As New DataTable()

Dim dtCol As New DataColumn()
dtCol.ColumnName = "ReferenceID"
dtCol.DataType = GetType(SqlInt32)
dtCol.AllowDBNull = False

dtValues.Columns.Add(dtCol)
dtValues.PrimaryKey = {dtCol}

Public Shared Sub ExecStoredProc(ByVal ProcName As String, ByRef connection As SqlConnection, ByRef dtValues As DataTable, ByVal ParamArray args() As Object)
    Dim sqlCommand As New SqlCommand()

    For i = 0 To args.Length - 1 Step 2
        sqlCommand.Parameters.AddWithValue(CStr(args(i)), args(i + 1))
    Next

    sqlCommand.CommandText = ProcName
    sqlCommand.CommandType = CommandType.StoredProcedure
    sqlCommand.Connection = connection

    Dim sqlAdp As New SqlDataAdapter(sqlCommand)
    ' Fill the table to mess around with.
    sqlAdp.Fill(dtValues)

End Sub

但是,我得到的错误是:

  

无法启用约束。一行或多行包含违反非null,唯一或外键约束的值。

我的存储过程我打电话是一个简单的

Select ID 
From TableName 
Where Reference = @Reference

没有任何条件,我已经过测试,它返回了大约19条独特的记录。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

您正在表中定义一个名为“ReferenceID”的非空主键数据列:

Dim dtCol As New DataColumn()
dtCol.ColumnName = "ReferenceID"
dtCol.DataType = GetType(SqlInt32)
dtCol.AllowDBNull = False

但是,您的sql查询未选择1ReferenceID1列,而是选择名为ID的列:

Select ID 
From TableName 
Where Reference = @Reference

因此,当你去填表时会出现错误:

  

无法启用约束。一行或多行包含违反非null,唯一或外键约束的值。

因为违反了您在“ReferenceID”上设置的非空,唯一约束。

将您的查询更改为:

Select ID as [ReferenceId]
From TableName 
Where Reference = @Reference

你应该设置(假设ID是唯一的而不是null)

相关问题