Imports System.Data.SqlClient Dim intCnt As Integer Dim intI As Integer Dim strQuery As String Dim strValue As String = "" Dim intValue As Integer Dim objDS As New DataSet Dim objDT As New DataTableFor intI = 0 To intCnt - 1 If strValue.Length = 0 Then'Create query as per u r requirement. strQuery = "Select max(LastPurPrc) from oitm" Else strQuery = "Select max(LastPurPrc) from oitm where LastPurPrc not in (" & strValue & ")" End If 'Create dataset objDS using query strQuery objDT = objDS.Tables(0) If objDT.Rows.Count > 0 Then intValue = objDT.Rows(0).Item(0) If strValue.Length = 0 Then strValue = CStr(intValue) Else strValue = strValue & "," & CStr(intValue) End If End If Next MessageBox.Show(intValue)