Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server except on stored procedure results

Tags:

sql-server

I want to do this but with stored procedure results:

select * from table where column=whatever
except
select * from table2 where column=whatever

so

exec sp1 args
except
exec sp2 args

my sps don't have return values they just take arguments and return the results of select statements

like image 661
Rob Sedgwick Avatar asked Mar 25 '14 11:03

Rob Sedgwick


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 do I call a stored procedure with no result?

If you are using .Net Framework application to call the stored procedure then take a look at SQLCommand.ExecuteNonQuery. This just executes stored procedure with no results returned. If problem is at SQL Server level then you are going to have to do something different (i.e. change the 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


1 Answers

Give this a go.

CREATE PROCEDURE usp_sp1_Except_sp2
@sp1 args     --<-- All the params sp1 Expects
@sp2 args     --<-- All the params sp2 Expects
AS
BEGIN
  SET NOCOUNT ON;

IF OBJECT_ID('tempdb..#SP1_Results') IS NOT NULL
DROP TABLE #SP1_Results

IF OBJECT_ID('tempdb..#SP2_Results') IS NOT NULL
DROP TABLE #SP2_Results


CREATE TABLE #SP1_Results
(
  -- Define table structure here
)

CREATE TABLE #SP2_Results
(
  -- Define table structure here
)


INSERT INTO #SP1_Results
EXECUTE dbo.sp1 @sp1

INSERT INTO #SP2_Results
EXECUTE dbo.sp2 @sp2

SELECT * FROM #SP1_Results
EXCEPT 
SELECT * FROM #SP2_Results

  SET NOCOUNT OFF;

END
like image 147
M.Ali Avatar answered Nov 18 '22 02:11

M.Ali