?
如果为空,是否可以修改以下查询以返回所有记录?
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ?;
?
如果为空,是否可以修改以下查询以返回所有记录?
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ?;
尝试这个:
SELECT *
FROM MY_TABLE
WHERE @parameter IS NULL OR NAME = @parameter;
您还可以使用函数IFNULL
, COALESCE
, NVL
,ISNULL
来检查空值。这取决于您的 RDBMS。
MySQL:
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = IFNULL(?,NAME);
或者
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = COALESCE(?,NAME);
甲骨文:
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = NVL(?,NAME);
SQL Server / SYBASE:
SELECT NAME, SURNAME FROM MY_TABLE WHERE NAME = ISNULL(?,NAME);
下一个。查询将处理名称(表列值)也可以为 NULL 的情况:
SELECT NAME, SURNAME FROM MY_TABLE WHERE COALESCE(NAME,'') = COALESCE(?,NAME,'');
SELECT NAME
FROM MY_TABLE
WHERE NAME LIKE CASE WHEN ? IS NOT NULL THEN ? ELSE '%' END
这将完美地工作,但它只会返回非空值。