Dynamic SQL (EXECUTE) as condition for IF statement

后端 未结 3 2005
予麋鹿
予麋鹿 2020-12-03 21:28

I want to execute a dynamic SQL statement, with its returned value being the conditional for an IF statement:

IF EXECUTE \'EXISTS (SELECT 1 FROM         


        
相关标签:
3条回答
  • 2020-12-03 22:00
    SET @SQLQUERY='SELECT 1 FROM mytable'
    
    EXEC (@SQLQUERY)
    If @@RowCount >0  THEN
    
    0 讨论(0)
  • 2020-12-03 22:05

    Matt,

    From the syntax above, you're writing PL/pgSQL, not SQL. On tht assumption, there are two ways to do what you want, but both will require two lines of code:

    EXECUTE 'SELECT EXISTS (SELECT 1 FROM ' || table_variable || ' );' INTO boolean_var;
    
    IF boolean_var THEN ...
    

    Or:

    EXECUTE 'SELECT 1 FROM ' || table_variable || ' );';
    
    IF FOUND THEN ...
    

    "FOUND" is a special variable which checks if the last query run returned any rows.

    0 讨论(0)
  • 2020-12-03 22:16

    This construct is not possible:

    IF EXECUTE 'EXISTS (SELECT 1 FROM mytable)' THEN ...

    You can simplify to:

    IF EXISTS (SELECT 1 FROM mytable) THEN ...
    

    But your example is probably just simplified. For dynamic SQL executed with EXECUTE, read the manual here. You can check for FOUND after RETURN QUERY EXECUTE:

    IF FOUND THEN ...
    

    However:

    Note in particular that EXECUTE changes the output of GET DIAGNOSTICS, but does not change FOUND.

    Bold emphasis mine. For a plain EXECUTE do this instead:

    ...
    DECLARE
       i int;
    BEGIN
       EXECUTE 'SELECT 1 FROM mytable';
    
       GET DIAGNOSTICS i = ROW_COUNT;
    
       IF i > 0 THEN ...
    

    Or if opportune - in particular with only single-row results - use the INTO clause with EXECUTE to get a result from the dynamic query directly. I quote the manual here:

    If a row or variable list is provided, it must exactly match the structure of the query's results (when a record variable is used, it will configure itself to match the result structure automatically). If multiple rows are returned, only the first will be assigned to the INTO variable. If no rows are returned, NULL is assigned to the INTO variable(s).

    ...
    DECLARE
       _var1 int;  -- init value is NULL unless instructed otherwise
    BEGIN
    
    EXECUTE format('SELECT var1 FROM %I WHERE x=y LIMIT 1', 'my_Table')
    INTO    _var1;
    
    IF _var1 IS NOT NULL THEN ...
    
    0 讨论(0)
提交回复
热议问题