Visual Basi c 2019: вызов SQL Серверная хранимая процедура и сохранение возвращаемого значения - PullRequest
0 голосов
/ 31 января 2020

В настоящее время я выполняю миграцию приложения VB6 на VB. NET и у меня возникают проблемы с получением возвращенного значения из хранимой процедуры.

Эта процедура возвращает счетчик (@count int output). Это прекрасно работает в VB6, поэтому я уверен, что хранимая процедура в порядке, и мой современный код VB 2019 является проблемой.

Этот код выполняет процедуру, но при попытке извлечь возвращенное целое число возникают ошибки. Я предполагаю, что мне не нужно DataTable для захвата возвращаемого значения, но я не могу понять, какую настройку мне нужно сделать. Я пытался QuickWatch переменных (используя VS 2019), но я не вижу ничего заполняемого хранимой процедурой в любой точке цепочки.

' Create & Call SQL Server stored procedure to obtain the count
Dim respondent_count_Command = New SqlCommand
respondent_count_Command.Connection = conn
respondent_count_Command.CommandType = CommandType.StoredProcedure

' Declare output parameter
Dim param_count = New SqlParameter()
param_count.ParameterName = "@Count"
param_count.SqlDbType = SqlDbType.Int
param_count.Direction = ParameterDirection.Output
respondent_count_Command.Parameters.Add(param_count)

' Execute the procedure
respondent_count_Command.CommandText = "[target_db].dbo.[p_XPR_ExcelExporting_Ansbooks_Count]"
Dim respondent_count_dt = New DataTable
respondent_count_dt.Load(respondent_count_Command.ExecuteReader())
conn.Close()

' Store the returned value in a dataRow. This value is expected to be an INTEGER
Dim ques_number_rows() As DataRow = respondent_count_dt.Select()

AnsBookCount = ques_number_rows(0)(0)

Ошибка:

System.IndexOutOfRangeException: «Индекс находился за пределами массива»

1 Ответ

1 голос
/ 31 января 2020

Предполагается, что хранимая процедура имеет один выходной параметр и не возвращает наборов результатов. Просто беги

Dim respondent_count_Command = New SqlCommand
respondent_count_Command.Connection = conn
respondent_count_Command.CommandType = CommandType.StoredProcedure

' Declare output parameter
Dim param_count = New SqlParameter()
param_count.ParameterName = "@Count"
param_count.SqlDbType = SqlDbType.Int
param_count.Direction = ParameterDirection.Output
respondent_count_Command.Parameters.Add(param_count)

' Execute the procedure
respondent_count_Command.CommandText = "[target_db].dbo.[p_XPR_ExcelExporting_Ansbooks_Count]"

respondent_count_Command.ExecuteNonQuery()

AnsBookCount = param_count.Value
...