Microsoft SQL Server SELECT语句

时间:2013-04-18 07:06:43

标签: sql-server vb.net select

我需要帮助从数据库表中检索ReceiptNO列,并将其保存到TextBoxLabel进行引用。

CODE:

Dim da2 As New SqlDataAdapter
da2.SelectCommand = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=@PaidFor AND RegNO=@RegNO)")
da2.SelectCommand.Parameters.Add("@paidFor", SqlDbType.VarChar).Value = cbMonth.Text
da2.SelectCommand.Parameters.Add("@RegNO", SqlDbType.Int).Value = lblRegNO.Text

cn.Open()
da2.Update(ds.Tables("Receipt"))
'da2.SelectCommand.ExecuteNonQuery()
da2.SelectCommand.ExecuteReader()
cn.Close()

1 个答案:

答案 0 :(得分:0)

您需要使用SqlDataReader,然后启动循环以读取返回的值
假设ReceiptNO是文本字段

,此示例将起作用
cn.Open()
Dim reader = da2.SelectCommand.ExecuteReader()
while reader.Read()
    textBox1.Text = reader("ReceiptNO").ToString()
End While

或者,如果您确定您的查询返回零或只有一条记录而您只对ReceiptNO字段感兴趣,那么您可以使用ExecuteScalar

Dim cmd = New SqlCommand("SELECT RecepitNO FROM Receipt WHERE (PaidFor=@PaidFor AND RegNO=@RegNO)")
cmd.Connection = cn
cmd.Parameters.Add("@paidFor", SqlDbType.VarChar).Value = cbMonth.Text
cmd.Parameters.Add("@RegNO", SqlDbType.Int).Value = lblRegNO.Text
cn.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
    textBox1.Text = result.ToString()
End If

Here the MSDN docs on ExecuteScalar