Is there a faster way to determine if a record exists in a database table than using a "Select * From Table" query. Yes; use an "If Exists" Dynamic Sql or Stored Procedure to increase performance of the query.
Many times you need to determine if a record exists in a table, and you might have used code such as shown below.
| Private Function IsUserExtant(ByVal user As String) As Boolean Dim dt As New DataTable Dim SQL As String Dim conn As New SqlConnection(ConnectionString) SQL = "select * from tbl_users " SQL &= "where username = '" & user & "' " Dim cmd As New SqlCommand(SQL, conn) ' the DataAdapter will open and close the connection ' automatically, so we don't bother with that Dim da As New SqlDataAdapter(cmd) da.Fill(dt) ' if dt.rows.count > then return true, else false Return dt.Rows.Count > 0 End Function |
| Private Function IsUserExtantFast(ByVal user As String) As Boolean Dim SQL As String Dim conn As New SqlConnection(ConnectionString) SQL &= "if exists(select username from tbl_stats_assigned " SQL &= "where username = '" & user & "') " SQL &= " select 1 as extant " SQL &= "else " SQL &= " select 0 as extant " Dim cmd As New SqlCommand(SQL, conn) cmd.Connection.Open() Dim i As Integer = cmd.ExecuteScalar() conn.Close() Return i > 0 End Function |
| Private Function IsUserExtantCallSP(ByVal user As String) As Boolean Dim conn As New SqlConnection(ConnectionString) Try conn.Open() Dim cmd As New SqlCommand("QuickCheck", conn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@username", CObj(user)) Dim i As Integer = cmd.ExecuteScalar Return i > 0 Catch ex As System.Exception MsgBox(ex.ToString) Return False Finally Try If Not conn Is Nothing AndAlso conn.State = ConnectionState.Open Then conn.Close() End If Catch End Try End Try End Function |