简体   繁体   中英

Dynamic SQL in Teradata Stored Procedure using conditionals

I am attempting to create a user-friendly stored procedure in Teradata that accepts a number of variables and outputs a result table based on the inputs. I'm building the query in SQL Assistant (provider version 14.0.0.0). For example...

Call statement...

CALL spAddressLookup
 ('?AcctNum', '?LastName', '?FirstName'
  ,'?Address' , '?City', '?State', '?ZipCode'
  ,'?Company', '?Email', '?Balance', ReturnCode)  ;

The create statement...

CREATE PROCEDURE spAddressLookup(IN pAcctNum VARCHAR(25)
 ,IN pLastName VARCHAR(100), IN pFirstName VARCHAR(100), IN pAddress VARCHAR(255)
 ,IN pCity VARCHAR(255), IN pState VARCHAR(100), IN pZipCode VARCHAR(15)
 ,IN pCompany VARCHAR(255), IN pEmail VARCHAR(255), IN pBalance VARCHAR(10) , OUT ReturnCode CHAR(5))
BEGIN

I would like to dynamically build a WHERE clause that only includes those variables in which the user enters a value for. I tried using an IF conditional statement inside my proc but the SET statement doesn't seem to play well inside the IF .

This is what I'm trying...

IF TRIM(pLastName) IS NOT NULL 
 THEN 
   SET strWHERE = ' AND ( a.LastName LIKE ''%' || pAcctNum || '%'' )'
END IF; 

Any ideas?

You can do it in this way:

IF pLastName IS NOT NULL
   SET strWHERE = ' AND ( a.LastName LIKE ''%' TRIM(pAcctNum) '%'' )'
END IF 

You don't need THEN in MSSQL and also pipes inside of LIKE

You can do one thing. First create variables for all your input parameters like this :

SET lv_pAcctNum  = CASE WHEN 'All' IN (''||pAcctNum ||'') THEN 1 ELSE (''||pAcctNum ||'') END;

Here 'All'signifies the entires where user has not entered anything (it could be null also as per your procedure design ).

After that in the dynamic sql where clause, use the variable like this :

'WHERE CASE WHEN ''All'' IN ('''||pAcctNum||''') THEN 1 ELSE Route_to_Market END IN  ('''||lv_pAcctNum||''' )'

This will achieve your goal

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.

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