I've the following query:
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ?;
Now I want that if '?' is NULL, all records have to be selected. How can I achieve this in SQL? Thanks
Try this:
SELECT *
FROM MY_TABLE
WHERE @parameter IS NULL OR NAME = @parameter;
You can also use functions IFNULL
, COALESCE
, NVL
, ISNULL
to check null value. It depends on your RDBMS.
MySQL :
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = IFNULL(?,NAME);
or
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = COALESCE(?,NAME);
ORACLE :
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = NVL(?,NAME);
SQL Server / SYBASE :
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ISNULL(?,NAME);
SELECT NAME
FROM MY_TABLE
WHERE NAME LIKE CASE WHEN ? IS NOT NULL THEN ? ELSE '%' END
This will work perfectly but it will return only the not null values.
The foll. query will handle the case where the Name (table column value) can also be NULL:
SELECT NAME, SURNAME FROM MY_TABLE WHERE COALESCE(NAME,'') = COALESCE(?,NAME,'');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.