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

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?

Related

Running a conditional sql script dependent on existence of database

I'm trying to automate a sql script to add a column to existing databases on a given system. The script will be run on a system with one database or a different one. The script should not cause error in any of the cases:
1. One of the two databases exists
2. Both databases exist
3. Neither database exists.
I tried this but I keep getting error when the database 'DatabaseName' does not exist. I want the script to be ignored in that case.
IF DB_ID('DatabaseName') IS NOT NULL
BEGIN
PRINT 'DatabaseName Exists'
IF COL_LENGTH('[DatabaseName].[dbo].[Table]', 'NewColumn') IS NULL
BEGIN
ALTER TABLE [DatabaseName].[dbo].[Table]
ADD [NewColumn] bit NOT NULL DEFAULT 0;
PRINT 'Modified DatabaseName.Table'
END
END
ELSE
BEGIN
PRINT 'DatabaseName Does Not Exist'
-- therefore do nothing
END
This gives me the error:
Msg 2702, Level 16, State 2, Line 6
Database 'DatabaseName' does not exist.
I had also tried different variations of
Use 'DatabaseName'
with the same or similar errors because they are not existent.
To clarify: it is okay if it does not exist. I am just trying to handle the error gracefully so an installation continues
Use dynamic SQL. The problem is occurring during the compilation phase of the code. Dynamic SQL will "hide" the reference to the database from the initial compilation phase.
For instance, in SQL Server, this looks like:
IF COL_LENGTH('[DatabaseName].[dbo].[Table]', 'NewColumn') IS NULL
BEGIN
exec sp_executesql N'
ALTER TABLE [DatabaseName].[dbo].[Table]
ADD [NewColumn] bit NOT NULL DEFAULT 0';
PRINT 'Modified DatabaseName.Table'
END
You can use a try catch block:
BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute code if error
END CATCH;

Ole db command & transactions. General Error

I have an OLE DB Command that originally contained a simple three line update:
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
and this worked fine, did exactly as expected and all was good.
I recently decided though that this has the potential to go wrong and do a lot of damage so i decided i would put it all in a transaction, monitor the rows affected and roll back if it changed more than what i was expecting, so i changed my update to this:
BEGIN TRY BEGIN TRAN UpdateCommissionsPaidPolNo
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
COMMIT TRAN END TRY BEGIN CATCH
ROLLBACK TRAN UpdateCommissionsPaidPolNo
PRINT 'UpdateCommissionsPaidPolicyNumber script failed'
SELECT
ERROR_MESSAGE() as ErrorMessage END CATCH
However this gave me the "Syntax error or general error" message that it usually gives. I remembered from a previous issue that sometimes it cant map parameters to the ?'s if they are embedded within other SQL, i thought that might be the issue so changed it to this just incase:
Declare #FNumber varchar(20) declare #LNumber varchar(20)
set #FNumber = ? set #LNumber = ?
BEGIN TRY BEGIN TRAN UpdateCommissionsPaidPolNo
update raw_CommissionPaid set PolicyNumber = #FNumber where
PolicyNumber = #LNumber
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
COMMIT TRAN END TRY BEGIN CATCH
ROLLBACK TRAN UpdateCommissionsPaidPolNo
PRINT 'UpdateCommissionsPaidPolicyNumber script failed'
SELECT
ERROR_MESSAGE() as ErrorMessage END CATCH
but from this i still get :
Syntax Error, permission violation or other non specific error
i realised it might be because of the print, or the returning of the error message, but removing them doesnt change anything, it still fails
im sure the sql is valid as i tested it in SQL server management studio.
Anyone faced this? Is there a setting im supposed to change to allow this kind of change?
Thanks in advance
After reading This site i learned that if i set the data flow tasks TransactionOption property to supported then if it fails it supposedly rolls the failing section back itself.
Armed with this knowledge i figured then the only thing i needed to do was make it realise that multiple rows being updated counted as an error. So changing it to just this:
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
should make it roll itself back.

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

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)

Logging into table in SQL Server trigger

I am coding SQL Server 2005 trigger. I want to make some logging during trigger execution, using INSERT statement into my log table. When there occurs error during execution, I want to raise error and cancel action that cause trigger execution, but not to lose log records. What is the best way to achieve this?
Now my trigger logs everything except situation when there is error - because of ROLLBACK. RAISERROR statement is needed in order to inform calling program about error.
Now, my error handling code looks like:
if (#err = 1)
begin
INSERT INTO dbo.log(date, entry) SELECT getdate(), 'ERROR: ' + out from #output
RAISERROR (#msg, 16, 1)
rollback transaction
return
end
Another possible option is to use a table variable to capture the info you want to store in your permanent log table. Table variables are not rolled back if a ROLLBACK TRANSACTION command is given. Sample code is below...
--- Declare table variable
DECLARE #ErrorTable TABLE
( [DATE] smalldatetime,
[ENTRY] varchar(64) )
DECLARE #nErrorVar int
--- Open Transaction
BEGIN TRANSACTION
--- Pretend to cause an error and catch the error code
SET #nErrorVar = 1 --- ##ERROR
IF (#nErrorVar = 1)
BEGIN
--- Insert error info table variable
INSERT INTO #ErrorTable
( [Date], [Entry] )
SELECT
getdate(), 'Error Message Goes Here'
RAISERROR('Error Message Goes Here', 16, 1)
ROLLBACK TRANSACTION
--- Change this to actually insert into your permanent log table
SELECT *
FROM #ErrorTable
END
IF ##TRANCOUNT 0
PRINT 'Open Transactions Exist'
ELSE
PRINT 'No Open Transactions'
The problem here is that logging is part of transaction that modifies your data. Nested transactions will not help here. What you need is to put you logging actions into a separate context (connection), i.e. make it independent from you current transaction.
Two options come to my mind:
use Service Broker for logging - put log data to queue, receive and save the data 'on the other side of the pipe' (i.e. in another process/connection/transaction)
use OPENQUERY - you will need to register you own server as a 'linked server' and execute queries 'remotely' (I know, this looks a little bit strange, but an option anyway ...)
HTH
Don't know if I'm thinking too simple, but why not just change the order of the error handler to insert AFTER the rollback??
if (#err = 1)
begin
RAISERROR (#msg, 16, 1)
rollback transaction
INSERT INTO dbo.log(date, entry) SELECT getdate(), 'ERROR: ' + out from #output
return
end
Checkout error handling in triggers.

SQL Statement Termination using RAISERROR

(SQL 2005)
Is it possible for a raiserror to terminate a stored proc.
For example, in a large system we've got a value that wasn't expected being entered into a specific column. In an update trigger if you write:
if exists (select * from inserted where testcol = 7)
begin
raiseerror('My Custom Error', 16, 1)
end
the update information is still applied.
however if you run
if exists (select * from inserted where testcol = 7)
begin
select 1/0
end
a divide by 0 error is thrown that actually terminates the update.
is there any way i can do this with a raiseerror so i can get custom error messages back?
In a trigger, issue a ROLLBACK, RAISERROR and then RETURN.
see Error Handling in SQL Server - Trigger Context by Erland Sommarskog
Can you not just add a CHECK constraint to the column to prevent it from being inserted in the first place?
ALTER TABLE YourTable ADD CONSTRAINT CK_No_Nasties
CHECK (testcol <> 7)
Alternatively you could start a transaction in your insert sproc (if you have one) and roll it back if an error occurs. This can be implemented with TRY, CATCH in SQL Server 2005 and avoids having to use a trigger.
Begin try
#temp number
#temp=1/0
End try
Begin catch
#errormsg varchar(100)
#errormsg=error_massage()
Raiseerror(#errormsg,16,1)
End catch
You should check for valid data prior to performing the update.
IF (#testvalue = 7)
RAISERROR("Invalid value.", 16, 1);
ELSE
UPDATE...