Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if SELECT Returns Any Rows in Stored Procedure

Tags:

I'm writing a basic SELECT query, something like:

SELECT id, pname, pnumber  FROM tableName  WHERE pnumber IS NOT NULL 

I'd like to then perform an INSERT by using the result of that SELECT like so:

IF {**the above SELECT query returned 0 rows**} BEGIN     INSERT INTO tableName (pname,pnumber) VALUES ('bob', '38499483') END 

My question is, how can I check for the **the above SELECT query returned 0 rows**?

like image 872
muttley91 Avatar asked Oct 10 '13 16:10

muttley91


People also ask

Can we select some columns from the stored procedure result?

And if try to use the SELECT statement with the procedure execution statement, the SQL Server will return an error. But still, there are two ways through which we can select some columns from the stored procedure result.

How to return data from a stored procedure in SQL Server?

A stored procedure in SQL Server does not return a table directly neither we can directly select data from a stored procedure. But, for this implementation, we can use a SELECT statement within a stored procedure to return table data, and then we can use table variables to store the data returned from a stored procedure.

How to remotely fetch columns from a stored procedure in SQL?

The FROM clause of a SELECT, INSERT, UPDATE, or DELETE statement are utilized with the OPENQUERY function. Now, we can use the SELECT statement with the OPENQUERY function to remotely fetch some table columns from a stored procedure.

What happens if multiple select statements are run during a procedure?

If multiple such SELECT statements are run during the execution of the stored procedure, multiple result sets will be sent to the client. This behavior also applies to nested TSQL batches, nested stored procedures and top-level TSQL batches. Examples of Returning Data Using a Result Set


2 Answers

IF NOT EXISTS (SELECT ...) BEGIN   INSERT ... END 

You could also do this, if you expect that the query might often return rows (especially a lot of rows), which may offer a better opportunity to short circuit:

IF EXISTS (SELECT ...) BEGIN   PRINT 'Do nothing.'; END ELSE BEGIN   INSERT ... END 

...since IF EXISTS will return immediately after it hits the very first row that matches.

I don't recommend using @@ROWCOUNT only because you will have to materialize (and ignore) the full result set every time.

like image 88
Aaron Bertrand Avatar answered Dec 09 '22 00:12

Aaron Bertrand


In MySQL you can check the number of rows returned from last SELECT query like this:

SELECT FOUND_ROWS(); 
like image 35
Sunil Kumar Avatar answered Dec 08 '22 23:12

Sunil Kumar