简体   繁体   English

如果查询未找到行,如何返回 null

[英]How to return a null if the query doesn't find a row

I am using SQL Server 2017. I am creating the whole MySQL Sakila database into mine in Azure Data Studio.我正在使用 SQL Server 2017。我正在将整个 MySQL Sakila 数据库创建到我的 Azure Data Studio 中。 I am currently stuck with functions, specifically with the line:我目前坚持使用功能,特别是以下行:

DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL;

This is my attempt, without the line that I mention it seems that the query has no errors.这是我的尝试,没有我提到的那一行,查询似乎没有错误。

CREATE FUNCTION inventory_held_by_customer (@p_inventory_id INT)
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
  DECLARE @v_customer_id INT;
  DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL; ---if the query finds no rows at all, then return a null
  SELECT @v_customer_id=customer_id
  FROM rental
  WHERE return_date IS NULL
  AND inventory_id = @p_inventory_id;

  RETURN(@v_customer_id);
END;

This is the original query for MySQL这是 MySQL 的原始查询

CREATE DEFINER=`root`@`localhost` FUNCTION `inventory_held_by_customer`(p_inventory_id INT) RETURNS int(11)
READS SQL DATA
BEGIN
  DECLARE v_customer_id INT;
  DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL;

  SELECT customer_id INTO v_customer_id
  FROM rental
  WHERE return_date IS NULL
  AND inventory_id = p_inventory_id;

  RETURN v_customer_id;
END

Thanks in advance, I appreciate the help!在此先感谢,感谢您的帮助!

Firstly, you do not need to add DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL;首先,您不需要添加DECLARE EXIT HANDLER FOR NOT FOUND RETURN NULL; to your function, it will return null if there is no result anyway.到您的 function,如果无论如何都没有结果,它将返回 null。

Secondly, scalar functions are slow, because they are executed in a separate context on every single row.其次,标量函数很慢,因为它们在每一行的单独上下文中执行。 It is much more performant to create an inline TVF instead:相反,创建内联 TVF 的性能要高得多:

CREATE FUNCTION inventory_held_by_customer (@p_inventory_id INT)
RETURNS TABLE
AS RETURN
(
  SELECT customer_id
  FROM rental
  WHERE return_date IS NULL
  AND inventory_id = @p_inventory_id
);

GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM