tags:

views:

184

answers:

6

I use a regex in my SQL statements for an app that look like this

SELECT * FROM table WHERE id = {{REPLACEME}}

However, sometimes I'm not giving a parameter to replace that string with. Is there a way to replace it with something that matches anything. I tried *, but that does not work.

+5  A: 
  1. SELECT * FROM table WHERE id = id will match all rows that have non-null id
  2. SELECT * FROM table WHERE id = id OR id IS NULL will match all rows.

id is probably a primary key, so you can probably use the former.

Jacob
I don't see how this solves the question. id = id is the same as no WHERE Clause.... (assuming NOT NULL restriction), right?
Frank V
I think the OP has a bunch of SELECT statements of the form seen in the question; since we need to replace {{REPLACEME}} with something, it should be the identity. Removing the WHERE clause would be better, but that's not what the OP asked for.
Jacob
+2  A: 

I can only describe my solution with an example. The @AllRec is a parameter:

Declare @AllRec bit
set @AllRec = {0|1}  --as appropriate

SELECT * 
FROM table 
WHERE 
   (
       id = {{REPLACEME}}
       and @AllRec = 0
   ) OR (
       @AllRec = 1
   )

In this solution, if @AllRec is 1 then everything is returned, ignoring the id filter. If @AllRec is zero, then the id filter is applied and you get one row. You should be able to quickly adapt this to your current regex solution.

Frank V
+1  A: 

Replace {{REPLACEME}} with

[someValidValueForYouIdType] OR 1=1
wtaniguchi
This does work in this case, but if the predicate becomes more complex, you might get unwanted results due to operator precedence.
Dave Costa
Yeah, but I presumed he wanted to get all results when no id is given. It sounds a little weird to me too, but I won't argue with his business logic.I would just return null if no records are found. And probably use some kind of prepared statements instead of regex replacing.
wtaniguchi
+1  A: 

Using the Regex-Replace option opens you up to SQL Injection attacks.

Assuming your language has support for parameterized queries, try this modified version of Jacob's answer:

SELECT * FROM table WHERE (id = @id OR @id IS NULL)

The catch is that you'll always have to provide the @id value.

Austin Salonen
A: 

Not sure what language your using, and this code kind of scares me but...


var statement = "SELECT * FROM table";

If REPLACEME is not empty Then
   statement += " WHERE id = {{REPLACEME}}"
End If


Dave
A: 
SELECT field1, field2
FROM dbo.yourTable
WHERE id = CASE WHEN @var IS NULL THEN
               id
           ELSE
               @var
           END
Chris Klepeis