gpt4 book ai didi

stored-procedures - DB2 存储过程 : Dynamically Building a Select Statement for cursor

转载 作者:行者123 更新时间:2023-12-02 15:39:28 25 4
gpt4 key购买 nike

我对存储过程还很陌生。我天真地认为我可以建立一个 select 语句如下。我做不到,你们中的一些人会对我的想法咧嘴一笑。

如何做我想做的事情?

提前致谢。

CREATE PROCEDURE GET_CUSTOMER_FOR_BORROWER_LETTER (


IN APPLICATION_ID INTEGER,
IN GET_GUARANTOR INTEGER,
IN GET_PREFERRED_CONTACT INTEGER
)

DYNAMIC RESULT SETS 1
READS SQL DATA

P1:BEGIN
DECLARE selectStmt VARCHAR(800);
DECLARE selectStmtPreferred VARCHAR(400);
DECLARE selectStmtApplicants VARCHAR(400);
DECLARE selectStmtGuarantor VARCHAR(400);


DECLARE cursor1 CURSOR WITH RETURN FOR
selectStmt -- will define this later, conditionally (babe in the woods :) )
OPEN cursor1;


set selectStmtPreferred = 'select "preferred applicant" as recipient_type, app.APPLICATION_ID, cust.KEY from application app, customer cust, application_detail appd where app.application_id = 407634 and app.APPLICATION_ID = appd.APPLICATION_ID and appd.PREFERRED_CONTACT_ID = cust.KEY';

set selectStmtApplicants = 'select "applicant" as recipient_type, app.APPLICATION_ID, cust.KEY from application app, applicant applc, customer cust where app.application_id = 407634 and applc.APPLICATION_ID = app.APPLICATION_ID and applc.CUST_ID = cust.CUST_ID';

set selectStmtGuarantor = ' union select "guarantor" as recipient_type ,app.APPLICATION_ID, cust.KEY from application app, application_guarantor appg, customer cust where app.application_id = 407634 and appg.APPLICATION_ID = app.APPLICATION_ID and appg.CUST_ID = cust.CUST_ID';

IF GET_PREFERRED_CONTACT = 1 THEN

IF GET_GUARANTOR = 1 THEN
SET selectStmt = concat (selectStmtPreferred,selectStmtGuarantor);
ELSE
SET selectStmt = selectStmtPreferred;
END IF;
ELSE
IF GET_GUARANTOR = 1 THEN
SET selectStmt = concat (selectStmtApplicants,selectStmtGuarantor);
ELSE
SET selectStmt = selectStmtApplicants;
END IF;
END IF;
selectStmt = concat (selectStmtPreferred,";");


END P1@

最佳答案

下次您需要构建一些动态 SQL 语句时试试这个。

DECLARE SELECT_STATEMENT VARCHAR(8000);

DECLARE cursor1 CURSOR WITH RETURN FOR SQL_STATEMENT;

...build dynamic sql here...

PREPARE SQL_STATEMENT FROM SELECT_STATEMENT;

OPEN cursor1;

需要说明的是,SQL_STATEMENT 可以是您想要的任何名称。只要确保它在 CURSOR 声明和 PREPARE 语句中是相同的即可。

关于stored-procedures - DB2 存储过程 : Dynamically Building a Select Statement for cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10410987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com