Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic SQL (EXECUTE) as condition for IF statement

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 mytable)' THEN

This generates the error ERROR: type "execute" does not exist.

Is it possible to do this, or is it necessary to execute the SQL before the IF statement into a variable, and then check the variable as the conditional?

like image 831
Matt Avatar asked Dec 09 '11 17:12

Matt


People also ask

Can we use if condition in SQL query?

Any T-SQL statement can be executed conditionally using IF… ELSE. If the condition evaluates to True, then T-SQL statements followed by IF condition in SQL server will be executed. If the condition evaluates to False, then T-SQL statements followed by ELSE keyword will be executed.

What statement do you use to execute a dynamic SQL statement?

Executing dynamic SQL using sp_executesql sp_executesql is an extended stored procedure that can be used to execute dynamic SQL statements in SQL Server. we need to pass the SQL statement and definition of the parameters used in the SQL statement and finally set the values to the parameters used in the query.

What are the three ways that dynamic SQL can be executed?

What are the three ways that Dynamic SQL can be executed? Writing a query with parameters. Using EXEC. Using sp_executesql.


1 Answers

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 simplified. For dynamic SQL executed with EXECUTE, read the manual here. You can check the special variable FOUND immediately after executing any DML command to see whether any rows here affected:

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';  -- something dynamic here

   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 ...
like image 135
Erwin Brandstetter Avatar answered Oct 12 '22 23:10

Erwin Brandstetter