SQL Conditional Formatting: Enhancing Your Database Queries

Is it possible to create a dynamic SQL statement based on user input using 3 textbox inputs?

var firstname = document.getElementById('firstname').value
var middle = document.getElementById('middle').value
var lastname = document.getElementById('lastname').value
var SQL

If all 3 fields are filled out:

SQL = "SELECT * FROM TABLE WHERE [Firstname] = '" + firstname + "' AND [Middle] = '" + middle + "' AND [Lastname] = '" + lastname + "'"

If 2 of the 3 fields are filled out:

SQL = "SELECT * FROM TABLE WHERE [Firstname] = '" + firstname + "' AND [Lastname] = '" + lastname + "'"

Is there a more concise way to handle this? Perhaps a shorter solution instead of evaluating each field and defining the SQL?

I was just curious, thought it wouldn't hurt to ask.

Jay

Answer №1

Perhaps a solution along these lines could be effective...

SQL = "SELECT * FROM TABLE WHERE 

  1 =
  (
  case
     when LEN('" + first + "') > 0  and LEN('" + last + "') > 0 and LEN('" + middle_name + "') > 0 then ([First] = '" + first + "' AND [Last] = '" + last + "' AND [MiddleName] = '" + middle_name + "')
     when LEN('" + first + "') = 0  and LEN('" + last + "') > 0 and LEN('" + middle_name + "') > 0 then ([Last] = '" + last + "' AND [MiddleName] = '" + middle_name + "')
     ...
  end
  )

Alternatively:

SQL = "SELECT * FROM TABLE WHERE 
(
  (LEN('" + first + "') > 0 AND [First] = '" + first + "') 
 OR 
   LEN('" + first + "') = 0
) 
AND (similar for next)
AND (similar for middle)"

Answer №2

If you pass the values as parameters into the query, it can help optimize performance and prevent spamming of the query cache.

SQL = " SELECT * 
    FROM TABLE 
    WHERE (@firstName is null OR [FirstName] = @firstName) 
      AND (@middle is null OR [Middle] = @middle)
          AND (@lastName is null OR [Lastname] = @lastName"

This method ensures that only one query plan is stored in the cache, improving efficiency.

Answer №3

Avoid making this mistake. Utilize parameterized queries as a safeguard against SQL injection for better security.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Express.static, the website functions properly but an error message "GET http://localhost:5000/index.js net::ERR_ABORTED 404 (Not Found)" is displayed

Having an issue with express.static. My project is a basic portfolio website that includes a form for sending emails. I referred to this tutorial on Nodemailer: Tutorial Nodemailer Github The problem arises within my index.html file (this example applies ...

Retrieving data from an array in VueJS

As a newcomer to Vue, I'm facing some difficulties in extracting a single value from an array. My Axios get request returns an array of users with fields such as name, display_name, role, and more. I have successfully retrieved all these values and di ...

`Switch up the backdrop upon selection`

I'm experimenting with bootstrap and hit a roadblock. I have radio buttons that I want to outline when not selected, and appear solid or "btn-primary" when selected. I could try achieving this with JavaScript by giving each button an individual ID, b ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

Delete the current code within the specified div element

Objective: The goal is to ensure that any HTML syntax code or data inside the specified <div id="feedEntries"></div> element is removed, leaving it empty. Issue: What specific syntax is required to remove all content within <div id="fe ...

Exploring the capabilities of the Contentful JavaScript SDK in conjunction with Native

I'm having some trouble getting the JavaScript Contentful SDK to work in my Nativescript app. As a newcomer to NativeScript, I might be missing something crucial. Hopefully, someone can lend a hand :) The module has been installed in my NativeScript ...

What are the advantages of utilizing buffer geometries in Three.js?

I have experience using both BufferGeometry and Geometry, so I feel comfortable with either. Even when I need to make frequent modifications, I tend to lean on BufferGeometry because although the code is more verbose, it's not overly complex. Can you ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Search for elements once they have been dynamically loaded using AJAX with the

I have a function called getItemID which searches for all the IDs under a specific parent ID (#search-output). This function works well when the ID (#test) is already loaded when the page loads. However, I am dynamically generating these IDs (#test) using ...

The validation process is functioning properly, however, the alert or message is failing to appear

After realizing that Safari is not compatible with the required HTML5 feature, I attempted to include a JavaScript validation script. Although the script successfully prevents the customer from advancing, the alert or message is not being displayed. <d ...

Sending information to Bootstrap 4 modal

Can you help me insert the variable into this link? <a href="#edit_task" data-toggle="modal"><i class="fas fa-edit fa-lg fa-fw"></i></a> This is my modal: <div class="modal fade" id=" ...

Is it possible to create a form inside a tooltip?

Looking to incorporate a jQuery feature into a form where a simple yes or no question appears upon hovering over it. However, encountering issues getting jQuery to recognize the dynamically created tooltip and submit alert function not working ("$('#w ...

Discovering and sorting an array in Vue.js based on IDs

Hello everyone, I've been attempting to filter my results using the filter and includes methods but it doesn't seem to be working. Does anyone have a solution for this, perhaps involving includes or something similar? companies ids [1,2,3] user c ...

Can you explain the concept of a function value?

In the world of JavaScript (ECMAScript 5), functions are highly esteemed (referred to as "first-class functions"). This unique characteristic allows us to treat functions as expressions, which means they can produce values and even include other expressio ...

Rotating a cone in three.js using two points and a specified radius

Using the coordinates and radius provided in an example XML file, I am trying to create a cone. Is there a way to rotate the cone if I have the top vertex's coordinates and the center of the base? Here is an image for reference: Image ...

Determining the availability of a remote source in React: A step-by-step guide

Is there a way to verify the existence of a remote resource, such as a large zip file, without actually downloading the file? What is the most efficient method for checking the presence of the resource? ...

Modifying the value of a local variable results in a corresponding adjustment to the original global variable's value

Within my Node.js program, I have set up an array named "list" in the routes section. This array is populated with values from a function defined in the model. The code for this route looks like: var express = require('express'); var router = ex ...

I am currently working on a Node.js application generated with express-generator and am experimenting with integrating Primus websocket

Currently in the process of developing a nodejs app using express-generator. I'm facing an issue while trying to integrate the Primus websocket into my application. The issue arises when I do not include app.listen(port) in my app.js file, causing the ...