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**
?
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.
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.
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.
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
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.
In MySQL you can check the number of rows returned from last SELECT query like this:
SELECT FOUND_ROWS();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With