使用变量声明向SQL函数添加新参数

时间:2018-05-13 15:39:40

标签: sql postgresql

我正在尝试向以下SQL函数添加第三个参数:

CREATE OR REPLACE FUNCTION community.publish_photo_story(
  p_story_id BIGINT,
  p_author_id INT
)
RETURNS TABLE (
  status VARCHAR(25),
  message VARCHAR(255)
)
AS
$func$
DECLARE
  v_photo_id BIGINT;
  v_caption TEXT;
  v_primary_photo VARCHAR(255);
  v_thumbnail_photo VARCHAR(255);
  v_tag_codes VARCHAR[];
  v_tag_ids INT[];
  v_status VARCHAR(25) := 'success';
  v_message VARCHAR(255) := 'Photo Story has been successfully published';
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM community.story
    WHERE story_id = p_story_id
      AND published_state = 'in-progress'
      AND is_deleted = false
      AND author_id = p_author_id) THEN

    v_status := 'error';
    v_message := 'The story cannot be published';

    RETURN QUERY SELECT v_status, v_message;
    RETURN;
  END IF;

  SELECT photo_id, caption INTO v_photo_id, v_caption
  FROM community.moment
  WHERE story_id = p_story_id
  ORDER BY display_order ASC 
  LIMIT 1;

  SELECT b_secured_url, t_secured_url INTO v_primary_photo, v_thumbnail_photo
  FROM core.photo
  WHERE photo_id = v_photo_id;

  WITH tags AS (
    SELECT c.tag_id, c.tag_code
    FROM community.story_tag as ct
    INNER JOIN community.tag as c
    ON ct.tag_id = c.tag_id
    WHERE ct.story_id = p_story_id
  ) SELECT
      array_agg(tag_id),
      array_agg(tag_code)
    INTO
      v_tag_ids,
      v_tag_codes
    FROM tags;

  UPDATE community.post
  SET post_text = concat(v_caption),
    last_updated_date = now()
  WHERE story_id = p_story_id;

  -- Substring caption to 160 chars for preview content
  IF length(v_caption) > 160 THEN
    v_caption := concat(substr(v_caption, 0, 160), '...');
  END IF;

  UPDATE community.story
  SET
    preview_content = v_caption,
    primary_photo = v_primary_photo,
    thumbnail_photo = v_thumbnail_photo,
    published_state = 'done',
    last_updated_date = now()
  WHERE story_id = p_story_id;

  INSERT INTO audit.story_history(
    story_id,
    acted_by_id,
    log_message)
  VALUES(
    p_story_id,
    p_author_id,
    'Photo story has been published');

  RETURN QUERY SELECT v_status, v_message;

END;
$func$ LANGUAGE plpgsql;

我应该添加一个新参数primary_photo,直观地说,这意味着我应该像这样修改参数:CREATE OR REPLACE FUNCTION community.publish_photo_story(p_story_id BIGINT, p_author_id INT, p_primary_photo VARCHAR)。但是,如果我仍然保留我声明变量v_primary_photo VARCHAR(255)的部分,我仍然感到困惑。如果不是因为v_primary_photo在其他地方被多次引用的事实,我会省略它。

简而言之,我如何确保v_primary_photo的任何现有实例都具有新参数p_primary_photo的值?

0 个答案:

没有答案