SQL - Raise error in Sproc when the select result set is empty - sql

I am trying to execute a stored procedure within a SQL JOB step (SQL Server 2005).
I want to Raise error and fail the job step when the result set of the stored procedure I am executing is not empty.
what my stored procedure does is --I have a select statement where the rows are displayed if the current date is equal to the date in one of the columns of a table.
SELECT
Holiday_date
from tblHolidays
where
CONVERT(VARCHAR(10),GETDATE(),101) = CONVERT(VARCHAR(10),Holiday_date,101)
If the result set is empty, I want to succeed the job step and proceed with the next job step.
Any thoughts on how to get this working.
Thanks

You can try RAISERROR althought I can't remember if this will cause the whole job to fail, if it does try one of the warning severity levels.
IF ##ROWCOUNT > 0
RAISERROR ('found data', 16, 1)

Related

Execute Stored Procedure based on date

I'm calling a stored procedure which contains an insert statement using another stored procedure. I am looking to perform the insert operation only if it is the first of the month. How do I add a condition in the execute statement that runs the stored procedure only on the first of each month?
I have tried the normal exec statement but am not sure how to add the first of month condition to this
EXEC SProc_test;
Assuming you are just interested in the condition, as opposed to a method of scheduling it then the following will only run on the 1st of the month.
if datepart(day, getdate()) = 1 begin
exec Sproc_test;
end;

SSIS Looping with Return Value from Stored Procedure

I am trying to create a SSIS Package that loops based on the return value of a stored procedure run in the loop. I keep getting a super NOT helpful error of:
"Error: 0xC002F210 at Load Order, Execute SQL Task: Executing the query "EXEC ? = [Load_Focus_OrderNum] ?, 1" failed with the following error:
"Value does not fall within the expected range.".
Possible failure reasons:
Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Load Order"
Here is my setup:
The Load Order stored procedure loads a table with 500 orders at a time, then the last order number is returned (I have confirmed it returns correctly).
DECLARE #spOut int
EXEC #spOut = Load_Focus_OrderNum 1, 1
PRINT #spOut
Returns 638 as expected
I then want it to process the next 500 starting at the next order.
I'm calling my stored procedure with:
EXEC ? = sp_LoadOrders ?, 1
Procedure snippet:
ALTER PROCEDURE [dbo].[LoadOrders]
(#PK_ID INT, #OrdType INT)
AS
-- Loads OrderNumTbl table
RETURN (SELECT TOP 1 ID FROM OrderNumTbl ORDER BY ID DESC)
GO
My parameter mapping for it is:
And my expressions for the loop are:
What am I missing? Any help is appreciated!
In the parameter Mapping section, replace the parameter name value with the parameter index >> replace #OrderID with 0 and #T1_ID with 1
References
SSIS: Value does not fall within the expected range
SQL Server Central - SSIS: Value does not Fall Within the Expected Range
Parameters and Return Codes in the Execute SQL Task

Why is my code not returning an error message when ##ROWCOUNT=0?

I created the below sp. When I execute it and insert an ID that does not exist, I want an error message to appear. However, the error message does not get printed... Does anyone can help me understand what I'm doing wrong please? Thank you
create procedure campaign_data
#campaign_ID bigint
as
begin
select campaignname,totalspend,clicks,impressions,totalspend/clicks as cpc
from DSP_RawData_Archive
where #campaign_ID=Campaign_ID
end
exec campaign_data 2
if ##ROWCOUNT=0 print 'Campaign_ID does not exist'
The PRINT statement will be displayed under the Messages tab on the results window if you are using SSMS and doesn't affect control flow.
Try throwing an error using RAISERROR with high enough severity (the middle parameter), which can affect control flow (jumps to CATCH or stops execution, for example).
IF ##ROWCOUNT = 0
RAISERROR('Campaign_ID does not exist', 15, 1)
The problem here is the scope of your ##ROWCOUNT. ##ROWCOUNT returns the number of effected rows of the last executed statement in a batch, in this case that from exec campain_data 2 and not that from the first select. Another example:
BEGIN TRAN
SELECT 0 WHERE 1 = 0
PRINT ##ROWCOUNT -- Displays 0
EXEC dbo.DoSomething -- Say this procedure returns 2 rows...
PRINT ##ROWCOUNT -- Displays 2
COMMIT
Another thing here is that you maybe want to show a proper error message in your scenario (instead of a simple PRINTed line). You can do achieve this using either
RAISERROR('Display my custom error message via RAISERROR!',16,1)
or
THROW 50000,'Display my custom error message via THROW!',1
Helpful article:
http://sqlhints.com/2013/06/30/differences-between-raiserror-and-throw-in-sql-server/
Try :
create procedure campaign_data
#campaign_ID bigint
as
begin
select campaignname,totalspend,clicks,impressions,totalspend/clicks as cpc
from DSP_RawData_Archive
where #campaign_ID=Campaign_ID
end
exec campaign_data 2
IF (SELECT ##rowcount) = 0
SELECT 'Campaign_ID does not exist'
I tried your stored procedure in Sequel Server Management Studio, and I saw the right response in message tab.
Where are you trying it?

How to get the last executed SQL statement in HANA?

I am inside a SQLScript procedure and would like to return the last SQL Statement from this procedure, like the last rowcount:
/********* Begin Procedure Script ************/
BEGIN
select 1 as "my_data" from dummy;
select '::last_SQL' as "last executed sql" from dummy;
select ::ROWCOUNT as "rowcount" from dummy;
END;
/********* End Procedure Script ************/
The column "last executed SQL" should be populated with select 1 as "my_data" from dummy in this case. Is there any variable holding the last statement (or any easy way to retrieve the query plan)?
Maybe you can query sys.m_sql_plan_cache system view
Please check following SELECT statement
select
statement_string, last_execution_timestamp
from SYS.M_SQL_PLAN_CACHE
where user_name = 'KODYAZ'
order by last_execution_timestamp desc;
I believe you can improve the query by introducing new filter criteria.
There is no way to programmatically get the last executed SQL statement in SQLScript. This is due to the fact that not all statements will be executed in the form and order as they appear in the source code.
If you want to analyse the performance of a procedure, you can run PlanViz against the procedure call. Generally, there is no such thing as "the performance of a procedure/function" as they always occur in a specific context.
If used within a SQL query, things like query-transformation can radically change the way certain results are computed.

What determines success or failure of SQL Server Job?

I have a query that I want to run in a SQL Server job. I would like to have the query report success if the query returns 1 or more rows, and to return failure if the query does not reutrn and rows. How would I go about doing this?
I think you will have to do this within the query:
IF ##ROWCOUNT < 1
BEGIN
RAISERROR('No records returned',16,1)
RETURN
END
If no rows are returned, an error will occur and the job will have a failure status.
Have a step that checks the count and calls RAISERROR or THROWs if there are no rows.