Skip to content
Advertisement

how can i set the parameters for the sql query optional?

I build a Web Service in ASP.Net which sends me a list of rooms.

The parameters are id’s which are separated by a comma.

I saved them to a string and build a sql select query.

When I send all 4 parameters I everything works fine and I get a result. But when I send less then 4 I get an error.

How can I set my the parameters optional in the sql query to select just the values I entered?

Here is my code so far:

Thanks in advance for your help.

Advertisement

Answer

Imagine the parameter REGION_ID is an empty string. That part of your query will be something like:

Because in AND REGION_ID IN (" + regionid + ")" the regionid variable will be replaced with an empty string. This is not valid SQL syntax so you’ll get that exception.

Declare a function like this:

Then change your code to build the query in this way:

WARNING: DO NOT USE this code in production or when the input comes from the user because it’s vulnerable to SQL injection. For better approaches (do not stop to the accepted answer) see Parameterize an SQL IN clause

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement