Sample Header Ad - 728x90

Database Administrators

Q&A for database professionals who wish to improve their database skills

Latest Questions

31 votes
7 answers
51059 views
PostgreSQL alternative to SQL Server’s `try_cast` function
Microsoft SQL Server has what I consider a remarkably sensible function, `try_cast()` which returns a `null` if the cast is unsuccessful, rather than raising an error. This makes it possible to then use a `CASE` expression or a `coalesce` to fall back on. For example: SELECT coalesce(try_cast(data a...
Microsoft SQL Server has what I consider a remarkably sensible function, try_cast() which returns a null if the cast is unsuccessful, rather than raising an error. This makes it possible to then use a CASE expression or a coalesce to fall back on. For example: SELECT coalesce(try_cast(data as int),0); The question is, does PostgreSQL have something similar? The question is asked to fill in some gaps in my knowledge, but there’s also the general principle that some prefer a less dramatic reaction to some user errors. Returning a null is more easily taken in one's stride in SQL than an error. For example SELECT * FROM data WHERE try_cast(value) IS NOT NULL;. In my experience, user errors are sometimes better handled if there is a plan B.
Manngo (3145 rep)
Apr 14, 2018, 06:20 AM • Last activity: Aug 6, 2025, 04:15 PM
1 votes
2 answers
3939 views
Postgres: Insert all valid data into a table while logging errors
I am attempting to devise a method that will enable me to load data into a table which will load all valid data and log the invalid records. Ideally, I'd like to do this without looping through the data. I wrote an example, but it doesn't work as I would like: ``` do $$ declare myval varchar(64); v_...
I am attempting to devise a method that will enable me to load data into a table which will load all valid data and log the invalid records. Ideally, I'd like to do this without looping through the data. I wrote an example, but it doesn't work as I would like:
do
$$
declare
	myval varchar(64);
	v_error_message_text text;
begin
	create temporary table mytemp (mycol varchar(6));

	insert into mytemp(mycol)
		values ('abcdef'),('ghijkl'),('mnopqr'),('stuvwxyz')
	on conflict do nothing
	returning myval;

	select * from mytemp;
	
exception
	when others then
		get stacked diagnostics
			v_error_message_text = message_text;
		raise notice 'Value: %; Error: %', myval, v_error_message_text;
end;
$$
language plpgsql;
Obviously, the real example will get data from a SELECT statement that will be more complex and the target will be a static table. I would also like to be able to capture the offending values and insert them into a log table along with various error information from the get stack diagnostics clause. In the example, I would want the first 3 values to be loaded into the table and the fourth caught in the exception handler (it's too long for the column length). At this point, it seems that nothing gets loaded into the target table and I always get a NULL value for the variable. I appreciate any assistance! :)
SQL RV (11 rep)
Sep 15, 2021, 08:05 PM • Last activity: Jul 26, 2025, 01:06 PM
1 votes
1 answers
220 views
How to index of filter extended event files in Sql Server
I am collecting errors data using the error_reported event and saving the data on XEL files. The problem is that there are hundreds of thousands of errors over there and querying them can take a lot of time. One option is to prevent errors from being logged twice if they happened on the same object...
I am collecting errors data using the error_reported event and saving the data on XEL files. The problem is that there are hundreds of thousands of errors over there and querying them can take a lot of time. One option is to prevent errors from being logged twice if they happened on the same object in the same timestamp. I really don't think the second option is possible. Second option is to index the file in a way that it will be quick to filter errors by the error text and the object that caused them. So far I thought of creating a separate process that will run in the background and writes filtered values from the files to an indexed table, but its a bad solution. That process would need maintenance and could be expensive on IO resources. So far I didn't find a way to solve it on the extended event level. Does anyone have a better idea?
Yuval Perelman (111 rep)
Oct 28, 2018, 04:59 PM • Last activity: Jun 12, 2025, 02:01 AM
1 votes
1 answers
661 views
Lost connection to the database during COMMIT query: did the transaction succeed or not?
# PROBLEM I recently encountered the error 2013 in MySql (Lost connection to MySQL server during query) while executing the `COMMIT` statement for a transaction (the previous update statements succeeded). This was due to a network downtime error during the commit. Then I started a new connection, an...
# PROBLEM I recently encountered the error 2013 in MySql (Lost connection to MySQL server during query) while executing the COMMIT statement for a transaction (the previous update statements succeeded). This was due to a network downtime error during the commit. Then I started a new connection, and upon checking the transaction effects I could see that the transaction was indeed committed successfully and there were no errors (the changes were applied). # QUESTIONS How can I be 100% sure that the commit succeeded when there are errors during the COMMIT query? Did anyone find a similar problem? What would be the best approach here when this ambiguity arises? Is there a way to avoid this 'commit ambiguity'? # PREVIOUS RESEARCH I found some related questions to other databases and MySql here: - https://dba.stackexchange.com/questions/81408/is-a-postgres-long-running-query-aborted-if-the-connection-is-lost-broken/81424#81424 - https://dba.stackexchange.com/questions/215579/what-happens-if-the-database-nodes-network-fails-just-after-commit-and-before-r - https://dba.stackexchange.com/questions/284526/conditions-that-can-make-a-mysql-commit-query-fail - https://dba.stackexchange.com/questions/204691/what-if-a-connection-closes-in-the-middle-of-a-commit - https://stackoverflow.com/questions/3960189/can-a-commit-statement-in-sql-ever-fail-how But it doesn't seem that there is a way to avoid this problem? Thank you!
bruno-kakele (11 rep)
May 20, 2023, 04:47 PM • Last activity: Apr 19, 2025, 05:09 AM
20 votes
5 answers
76821 views
How to break SQL script execution
I am working on sql script and I am having a requirement of stop continuing the script if some conditions are not satisfied. When I Google it, I found the RaisError with 20 severity level will terminate it. But for some reasons I cannot use that option. Can please provide me what are the possible al...
I am working on sql script and I am having a requirement of stop continuing the script if some conditions are not satisfied. When I Google it, I found the RaisError with 20 severity level will terminate it. But for some reasons I cannot use that option. Can please provide me what are the possible alternatives to stop SQL script execution.
New Developer (473 rep)
Aug 29, 2013, 04:29 AM • Last activity: Apr 12, 2025, 11:30 AM
10 votes
4 answers
21404 views
How to log error details when using using try/catch for dynamic SQL backup commands
When issuing a backup command within a stored procedure that uses a try catch and dynamic sql, the error messages are very general when compared to running the backup command directly. Try/Catch within SP: begin try execute sp_executesql @sql; -- a backup command end try begin catch print ERROR_MESS...
When issuing a backup command within a stored procedure that uses a try catch and dynamic sql, the error messages are very general when compared to running the backup command directly. Try/Catch within SP: begin try execute sp_executesql @sql; -- a backup command end try begin catch print ERROR_MESSAGE(); -- save to log, etc. end catch Results in > 50000:usp_Backup:117: BACKUP DATABASE is terminating abnormally. wheareas issuing the raw command: backup DATABASE someDb to disk... Results in better details: > Lookup Error - SQL Server Database Error: A nonrecoverable I/O error > occurred on file "H:\FolderName\Filename.bak:" 112(There is not enough > space on the disk.). Is there a way to catch these details into variables within the stored procedure (to log, pass back to caller, for retry logic)? It seems the details are coming through on the message channel but I would like them available within the SP.
crokusek (2110 rep)
Jun 25, 2012, 07:41 PM • Last activity: Mar 23, 2025, 08:41 PM
5 votes
1 answers
412 views
What is a good way to handle an error while parsing a T-SQL command that doesn't exist on an older version of SQL Server?
I am trying to grant the [CONNECT ANY DATABASE] permission to a specific SQL account on multiple instances. However, one server is running SQL Server 2012 and that permission was not introduced until 2014. I've been looking for additional ways to handle this particular error gracefully so that the r...
I am trying to grant the [CONNECT ANY DATABASE] permission to a specific SQL account on multiple instances. However, one server is running SQL Server 2012 and that permission was not introduced until 2014. I've been looking for additional ways to handle this particular error gracefully so that the remainder of the script which grants additional permissions gets executed. Currently, the script throws a terminating parser? error. Here is the problem section of code: IF NOT EXISTS ( SELECT * FROM sys.server_permissions AS perm INNER JOIN sys.server_principals AS prin ON perm.grantee_principal_id = prin.principal_id WHERE perm.permission_name = 'CONNECT ANY DATABASE' AND prin.name = '' ) BEGIN GRANT CONNECT ANY DATABASE TO []; END; The error is: "*Incorrect syntax near 'CONNECT'.*" I tried the following which didn't work. 1. Using a TRY-CATCH block 2. Adding additional logic to the IF condition
( SERVERPROPERTY('servername')  '' )
I did finally find a viable solution but wanted to learn about other ways people have resolved a similar issue. IF NOT EXISTS ( SELECT * FROM sys.server_permissions AS perm INNER JOIN sys.server_principals AS prin ON perm.grantee_principal_id = prin.principal_id WHERE perm.permission_name = 'CONNECT ANY DATABASE' AND prin.name = '' ) AND ( SERVERPROPERTY('servername') '' ) BEGIN DECLARE @String NVARCHAR(150) SET @String = 'GRANT CONNECT ANY DATABASE TO [];'; EXEC sp_executesql @Command = @String; END
AABCDS (119 rep)
Jan 16, 2025, 03:36 PM • Last activity: Jan 17, 2025, 07:19 AM
2 votes
1 answers
258 views
RAISERROR / THROW and sp_start_job Termination Behaviour
Given the following SQL Server Agent job USE [msdb] GO BEGIN TRANSACTION DECLARE @ReturnCode INT SELECT @ReturnCode = 0 IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1) BEGIN EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB',...
Given the following SQL Server Agent job USE [msdb] GO BEGIN TRANSACTION DECLARE @ReturnCode INT SELECT @ReturnCode = 0 IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1) BEGIN EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]' IF (@@ERROR 0 OR @ReturnCode 0) GOTO QuitWithRollback END DECLARE @jobId BINARY(16) EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Do Nothing', @enabled=1, @notify_level_eventlog=0, @notify_level_email=0, @notify_level_netsend=0, @notify_level_page=0, @delete_level=0, @description=N'No description available.', @category_name=N'[Uncategorized (Local)]', @owner_login_name=N'Me', @job_id = @jobId OUTPUT IF (@@ERROR 0 OR @ReturnCode 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Wait', @step_id=1, @cmdexec_success_code=0, @on_success_action=1, @on_success_step_id=0, @on_fail_action=2, @on_fail_step_id=0, @retry_attempts=0, @retry_interval=0, @os_run_priority=0, @subsystem=N'TSQL', @command=N'WAITFOR DELAY ''00:00:10''', @database_name=N'master', @flags=0 IF (@@ERROR 0 OR @ReturnCode 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1 IF (@@ERROR 0 OR @ReturnCode 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)' IF (@@ERROR 0 OR @ReturnCode 0) GOTO QuitWithRollback COMMIT TRANSACTION GOTO EndSave QuitWithRollback: IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION EndSave: GO And the following calling code EXEC msdb.dbo.sp_start_job @job_name = 'Do nothing' -- waits for 10 seconds WAITFOR DELAY '00:00:05' EXEC msdb.dbo.sp_start_job @job_name = 'Do nothing' -- fails, job still running WAITFOR DELAY '00:00:10' EXEC msdb.dbo.sp_start_job @job_name = 'Do nothing' -- should succeed I get the following error: Job 'Do nothing' started successfully. Msg 22022, Level 16, State 1, Line 25 SQLServerAgent Error: Request to run job Do Nothing (from User Me) refused because the job is already running from a request by User Me. Job 'Do nothing' started successfully. So we can see the second sp_start_job call failed because the job was still running, then SQL Server continued execution the failure is a Level 16 and when I do the following PRINT 'hello' RAISERROR ('error',16,1) PRINT 'hello' I get the same "fail and continue" behaviour hello Msg 50000, Level 16, State 1, Line 50 error hello however, if I do the following, which also raises a Level 16 error, the second print is not run PRINT 'hello' ;THROW 51000, 'error', 1; PRINT 'hello' hello Msg 51000, Level 16, State 1, Line 50 error The docs for THROW state > Any error that occurs in a THROW statement causes the statement batch to be terminated. The docs for RAISERROR state > The error is returned to the caller if RAISERROR is run: >Outside the scope of any TRY block. >With a severity of 10 or lower in a TRY block. >With a severity of 20 or higher that terminates the database connection. My questions is, is sp_start_job using RAISERROR rather than throw - I have looked into the definition and can't see if anywhere
SE1986 (2182 rep)
Dec 16, 2024, 12:00 PM • Last activity: Dec 16, 2024, 09:06 PM
3 votes
2 answers
2415 views
Long time, sporadic 'String or Binary data would be truncated.'
TL;DR: How can I diagnose the source of a very inconsistent, unreproducible *'String or Binary data would be truncated.'* error, when I am quite positive the problem isn't related to user data being to large to fit into SQL objects? ---------- I have a project that is a C# application which uses SQL...
TL;DR: How can I diagnose the source of a very inconsistent, unreproducible *'String or Binary data would be truncated.'* error, when I am quite positive the problem isn't related to user data being to large to fit into SQL objects? ---------- I have a project that is a C# application which uses SQL Server Express 2005 as a local database engine. The database is used to mostly cache data and very little processing or transforming is done within the local database. The exception to this is when I need to prepare locally cached data to use when a user prints a report from their application. In this case, the user calls a stored procedure and passes in a few variables. The stored procedure starts by deleting all data associated with the document being printed. In other words, it fully cleans the data cache before it begins. Next, it goes through a very long and complex process of consolidating and building information. Much of this information is stored in temp tables and after the process is finished, it copies the temp information into the report data tables. This application has existed for nearly 6 years. About once every few months, since the inception of the application, a random user has called me telling me that they have received a *'String or Binary data would be truncated.'* error. Furthermore, their application has historically worked perfectly, some times for years. Then, all of a sudden, they can't print from their application and they receive the above message from SQL Server. After receiving the error, they can't recover from it. In fact, every document they try to load (even one's that have worked minutes before the message appeared) are now impossible to generate because SQL Server keeps throwing this error. I know and understand the nature of this error. It's telling me that some data is larger than a specific field in which it's being inserted, however this doesn't make since in my context for two, main reasons. 1. I've never been able to reproduce this bug on any PC, but it is 100% consistent on the user's PC once it starts. 2. Across the years I've never been able to force this error to occur, regardless of the inputs I've stored in my associated data tables or passed to the stored procedure as parameters. The only way I've been able to fix this problem is to flag the user account to delete their local database. Once the user deletes their db, they rebuild and sync it with the server and everything works perfectly again. The failing stored procedure also has a ludicrous amount of data checks and washing routines, all because of this dumb error. I've never been able to isolate the problem nor solve it. I know that this type of question typically begs for the posting of code but I can't provide that. This is a BIG stored procedure and it contains some propitiatory details. Still, if anyone is aware of a SQL bug that could be caching something within the internals of SQL Server and produces this generic exception, I'd appreciate the information or your expert advice of where else to look for a solution. Please ask questions. I will comment and update my post as needed.
RLH (937 rep)
Mar 28, 2013, 03:06 PM • Last activity: Sep 11, 2024, 03:30 PM
8 votes
9 answers
88070 views
SSPI handshake failed with error code 0x8009030c, state 14
DESCRIPTION: SSPI handshake failed with error code 0x8009030c, state 14 while establishing a connection with integrated security; the connection has been closed. Reason: AcceptSecurityContext failed. The Windows error code indicates the cause of failure. [CLIENT: 10.XXX.XX.XX} ***The client address...
DESCRIPTION: SSPI handshake failed with error code 0x8009030c, state 14 while establishing a connection with integrated security; the connection has been closed. Reason: AcceptSecurityContext failed. The Windows error code indicates the cause of failure. [CLIENT: 10.XXX.XX.XX} ***The client address is different on different occasion Can i refer this problem to my network admin? is this a network issue or a sql server issue. Is there any other way other then changing the registry ? Can i safely ignore this error ?
SqlNovice (654 rep)
Nov 19, 2017, 11:50 PM • Last activity: Sep 9, 2024, 10:11 PM
0 votes
1 answers
107 views
How to get detailed error messages. Include table & column names & records. Conversion failed when converting the varchar value 'A' to data type int
I have an old, large (more than 140 lines), and complicated SQL query. It is joining many tables and has detailed WHERE conditions with values and a detailed GROUP BY part. **Query Structure** SELECT H.C1 H.C2 H.C3 D.C1 D.C2 D.C3 C.C1 C.C2 F.C1 F.C2 F.C3 FROM TBL1 H LEFT JOIN TBL2 D ON D.WH_ID = H.W...
I have an old, large (more than 140 lines), and complicated SQL query. It is joining many tables and has detailed WHERE conditions with values and a detailed GROUP BY part. **Query Structure** SELECT H.C1 H.C2 H.C3 D.C1 D.C2 D.C3 C.C1 C.C2 F.C1 F.C2 F.C3 FROM TBL1 H LEFT JOIN TBL2 D ON D.WH_ID = H.WH_ID LEFT JOIN TBL3 C ON H.CUST_ID = C.ID LEFT JOIN TBL4 F ON H.RECEIPT_ID = F.ID AND H.CUST_ID = F.CUST_ID WHERE DETAILED WHERE CONDITIONS GROUP BY GROUP COLUMNS ORDER BY ORDER BY COLUMNS **Error message** It gives Msg 245, Level 16, State 1, Line 2 Conversion failed when converting the varchar value 'A' to data type int. Completion time: 2024-09-03T09:41:07.2716887+03:00 enter image description here It is a superficial error messages, for which the specific table and column or the specific where condition the error is related to is an unknown. Moving step by step, I solved the problem, but the SQL Server Engine knows the table and column name that are related to the problem. Why doesn't it give this info in the error message? **Using Catch Block** BEGIN TRY SELECT H.C1 H.C2 H.C3 D.C1 D.C2 D.C3 C.C1 C.C2 F.C1 F.C2 F.C3 FROM TBL1 H LEFT JOIN TBL2 D ON D.WH_ID = H.WH_ID LEFT JOIN TBL3 C ON H.CUST_ID = C.ID LEFT JOIN TBL4 F ON H.RECEIPT_ID = F.ID AND H.CUST_ID = F.CUST_ID WHERE DETAILED WHERE CONDITIONS GROUP BY GROUP COLUMNS ORDER BY ORDER BY COLUMNS END TRY BEGIN CATCH SELECT ERROR_MESSAGE() AS ErrorMessage ,ERROR_NUMBER() AS ErrorNumber ,ERROR_SEVERITY() AS ErrorSeverity ,ERROR_STATE() AS ErrorState ,ERROR_PROCEDURE() AS ErrorProcedure ,ERROR_LINE() AS ErrorLine END CATCH; GO I tried to get detailed error messages with a Catch block but the result was the same. **Is it possible to configure SQL Server (may be with trace flags) or SSMS to give a detailed error messages, including related tables and columns?** enter image description here
Fevzi Kartal (338 rep)
Sep 3, 2024, 07:43 AM • Last activity: Sep 4, 2024, 05:05 AM
0 votes
1 answers
43 views
Passing contextual information to Postgres statements
To improve our insights on the health of some of our services, we've decided to improve our logging practices. One thing I've always wanted to explore was whether it's possible to easily correlate a Request landing on our servers with the outcome of the SQL statement that serves it. For example: - U...
To improve our insights on the health of some of our services, we've decided to improve our logging practices. One thing I've always wanted to explore was whether it's possible to easily correlate a Request landing on our servers with the outcome of the SQL statement that serves it. For example: - User Bob requests his plane ticket via an HTTP request - It lands on our server, I give that request a UUID. - To serve that request, I run this: SELECT * FROM plane_ticket WHERE user = 'bob'?. - The query happens to timeout; it exceeded the statement_timeout. - User is served an HTTP status code and 2 errors are logged, the HTTP error and the database error. These errors come from different systems, the webservice and Postgres. While I can do my investigations more-or-less, It's always a bummer that those 2 pieces of data are kind of disconnected. I'd much prefer if Postgres reported the SQL timeout error while somehow *including that request ID in the error log itself*. Only mechanism I can think of is correlating the request with the pid of the PG backend that's gonna serve me - is that the right way to go or is there a simpler way of going about this?
nicholaswmin (229 rep)
May 24, 2024, 05:04 AM • Last activity: May 24, 2024, 07:29 AM
0 votes
2 answers
136 views
Performance issue - using try catch to return data to service & how to use partition table with unique index
I'm working on enviorment SQL azure. I've got a stored procedure that runs from several AKS simultaneously and insert a message. So it's a race for who writes the message first and the rest fails. The insert fails due to Unique index and send the Id of the failed message to the service. here is the...
I'm working on enviorment SQL azure. I've got a stored procedure that runs from several AKS simultaneously and insert a message. So it's a race for who writes the message first and the rest fails. The insert fails due to Unique index and send the Id of the failed message to the service. here is the stored procedure:
CREATE OR ALTER PROCEDURE Saga.AddMessage
(
	@SagaIdentity NVARCHAR(256),
	@MessageId NVARCHAR(64),
	@SagaMessage NVARCHAR(MAX),
	@Created DATETIME2(7),
	@Updated DATETIME2(7),
	@SubscriptionStatus SMALLINT
)
AS
BEGIN
	BEGIN TRY
		INSERT INTO [Saga].[SubscribersMessages] ([SagaIdentity], [MessageId], [SagaMessage], [Created], [Updated], [SubscriptionStatus])
		SELECT @SagaIdentity, @MessageId, @SagaMessage, @Created, GETDATE(), @SubscriptionStatus    	
		WHERE NOT EXISTS (SELECT 1 FROM [Saga].[SubscribersMessages] WHERE MessageId = @MessageId);
	
		SELECT [Id] AS Results
		FROM [Saga].[SubscribersMessages] 
		WHERE MessageId = @MessageId
	END TRY
	BEGIN CATCH
		SELECT [Id] AS Results
			FROM [Saga].[SubscribersMessages] 
			WHERE MessageId = @MessageId
	END CATCH;
END
and here is the unique index :
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('Saga.SubscribersMessages','U') AND name = 'UX_SubscribersMessages_MessageId')
BEGIN
	CREATE UNIQUE INDEX UX_SubscribersMessages_MessageId
	ON [Saga].[SubscribersMessages] (MessageId);
END
I have a couple of problems with this service: 1. Peformance issue - I don't like the fact the the process rely CATCH on failed processed to return the Id. 2. I want to Partition the table using the Created field in order to truncate partition in the future and i get an error - Column 'Created' is partitioning column of the index 'UX_SubscribersMessages_MessageId'. Partition columns for a unique index must be a subset of the index key I thought about the MessageId as my Primary Key as it is unique but there are downsides to that as the MessageId is NVARCHAR(64). Here is the execution plan:
dexon (65 rep)
May 7, 2024, 08:12 AM • Last activity: May 9, 2024, 06:41 AM
17 votes
2 answers
8150 views
Does Oracle PL/SQL have a standard ASSERT routine?
I'd like to use an ASSERT routine functionally similar to the one found in other languages, i.e. a construct (be it a procedure, syntax...) ASSERT( , ) such that when the ` ` passed in the first argument is false an exception is raised with the specified ` ` descriptive message. I know this is trivi...
I'd like to use an ASSERT routine functionally similar to the one found in other languages, i.e. a construct (be it a procedure, syntax...) ASSERT( , ) such that when the ` passed in the first argument is false an exception is raised with the specified ` descriptive message. I know this is trivial to do by hand but **I'm asking if there's a standard one** provided with the DBMS. Having to write my own one or import one from 3rdy-party packages would be impractical, since I'd need it to be completely portable and transparent to every project I'm working on.
user881430 (281 rep)
Sep 5, 2012, 12:30 PM • Last activity: May 7, 2024, 03:07 AM
1 votes
1 answers
170 views
Does client timeout send the execution of a stored procedure from the TRY block to the CATCH block?
What happens when a client timeout occurs during the execution of a stored procedure that raises XACT_ABORT and wraps its body in TRY/CATCH blocks? I am looking at a bunch of procedures that generally can be converted to an MWE as follows: create or alter procedure ##ptx as begin try set xact_abort...
What happens when a client timeout occurs during the execution of a stored procedure that raises XACT_ABORT and wraps its body in TRY/CATCH blocks? I am looking at a bunch of procedures that generally can be converted to an MWE as follows: create or alter procedure ##ptx as begin try set xact_abort on waitfor delay '10:00' end try begin catch declare @xsx int = XACT_STATE() raiserror('XSX=%d', 16, 10, @xsx) with log, nowait end catch I created a test harness that logs into the server as SA, asynchronously calls such procedure, and times out the call after X seconds but earlier than the delay should run out. There are no new entries in the log, so it looks like the execution does not enter the CATCH block when a timeout occurs. Should it? If it should not, then what happens upon the client timeout?
Betty Liv (43 rep)
Apr 20, 2024, 10:38 PM • Last activity: Apr 21, 2024, 01:31 PM
0 votes
0 answers
117 views
Can I redirect rows on error in SSIS if the error happens within an "if condition", not while writing the column value?
I know how I redirect rows on error or truncation. That works if you have an error while you insert a value into the column. - Truncation: Say you have a string of 10 characters and you insert it into a column of `char(5)`. That is a truncation that you can redirect to an error output table. - Error...
I know how I redirect rows on error or truncation. That works if you have an error while you insert a value into the column. - Truncation: Say you have a string of 10 characters and you insert it into a column of char(5). That is a truncation that you can redirect to an error output table. - Error: Say you insert an int into a varchar(10) column. The data types will not match and the row is redirected to the error output table. But I do not seem to get a row redirected if an error happens inside the calculation of a column, and at [Changing MaximumErrorCount when executing maintenance plan](https://dba.stackexchange.com/questions/128973/changing-maximumerrorcount-when-executing-maintenance-plan/) , I was asked to make my remark a new question: > After changing MaximumErrorCount to a high number, I still did not get any redirected rows to the error table. It just stopped the job, but I would want the job to go on and throw only the erroneous rows out to the error table. My problem was that I casted a number as AS DECIMAL(4,2)) even though it had to be AS DECIMAL(5,2)), see [how to resolve DTS_E_OLEDBERROR. in ssis](https://stackoverflow.com/a/78176256/11154841) . But such an error should normally just redirect the row to the error table and not stop the job, shouldn't it? The string column could be built as such: check whether a number is bigger than 9 and output the string "warning, high number" in a column called "Warnings and checks". If then after years, a number 100 pops up the first time ever as a clear outlier that was never thought to happen, and if that number is cast to AS DECIMAL(4,2) inside such an "if condition" of a column even though it has to be AS DECIMAL(5,2), there is an error that stops the SSIS job. See also [SQL Query not throwing error even if the entered scale value is higher than specified](https://dba.stackexchange.com/questions/126227/sql-query-not-throwing-error-even-if-the-entered-scale-value-is-higher-than-spec) for another data type (here: numeric) question that would throw the same error. I want the SSIS job to go on and just redirect the row to the error table also if an error happens inside an "if condition". Changing the MaximumErrorCount to a high number does not fix it. Can it be done at all? Should it be done at all?
questionto42 (366 rep)
Mar 23, 2024, 11:53 AM • Last activity: Mar 23, 2024, 12:16 PM
2 votes
1 answers
1524 views
Catching exceptions and rolling back transactions
I am just trying to see if I understand [this][1] correctly: [1]: https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING > By default, any error occurring in a PL/pgSQL function aborts > execution of the function and the surrounding transaction I have a proced...
I am just trying to see if I understand this correctly: > By default, any error occurring in a PL/pgSQL function aborts > execution of the function and the surrounding transaction I have a procedure which does multiple insert operations on different tables, however at the moment I did not make them into a singular transaction. Does the above documentation mean that if an error were to occur all operations performed inside the procedure would be rolled back or do I need to catch exceptions and perform rollback/commit manually?
Lugoom485 (45 rep)
Feb 29, 2024, 11:35 AM • Last activity: Feb 29, 2024, 01:46 PM
0 votes
3 answers
119 views
How to exit the Azure SQL script to skip all remaining batches?
I have a Python script that glues together individual SQL scripts like: creating tables, creating views, creating functions, creating stored procedures... It produces the single installation SQL script. Having more "similar" databases in one SQL server and using SSMS, I would like to avoid the user...
I have a Python script that glues together individual SQL scripts like: creating tables, creating views, creating functions, creating stored procedures... It produces the single installation SQL script. Having more "similar" databases in one SQL server and using SSMS, I would like to avoid the user error by using the installation script for the unrelated database. The Python script basically just concatenates the individual scripts in the correct order with the GO command after each one. Like this: -- create_table_log.sql -------------------- IF (OBJECT_ID(N'dbo.log', 'U') IS NULL) BEGIN CREATE TABLE dbo.log ( ts datetime2 NOT NULL, user_ nvarchar(40) NOT NULL, msg nvarchar(MAX) NOT NULL, code int NOT NULL ) END GO ------------------------------------------- -- usp_log.sql -------------------- IF (OBJECT_ID(N'dbo.usp_log', 'P') IS NOT NULL) DROP PROCEDURE dbo.usp_log GO CREATE PROCEDURE dbo.usp_log @msg nvarchar(MAX), @code int = 0, @user nvarchar(40) = '' AS BEGIN SET NOCOUNT ON IF @user = '' SET @user = SYSTEM_USER INSERT dbo.log (ts, user_, msg, code) VALUES (SYSDATETIME(), @user, @msg, @code) PRINT @msg END My idea was to add the initial part that would check the name of the database and would exit the whole script early in the case. So, I have used: DECLARE @expected_dbname nvarchar(50) = 'xxx_db' DECLARE @this_dbname nvarchar(50) = DB_NAME() IF @this_dbname @expected_dbname BEGIN RAISERROR(N'Must be executed in the context of the ''%s'' database.', 0, 1, @expected_dbname) WITH NOWAIT RAISERROR(N'Was executed in the context of ''%s'' (early termination).', 11, 1, @this_dbname) WITH NOWAIT RETURN END GO ------------------------------------------- The RETURN ends execution only of the current batch. However, I was expecting that RAISERROR with severity 11 (*Indicates that the given object or entity doesn't exist.*) will end the execution in the SSMS console. It did not. **What is the correct way to stop execution immediately -- not executing even further batches in the same script?** As the batches (between GO) are executed kind of independently, it probably has to be the equivalent of the "cancel button" in the SSMS.
pepr (143 rep)
Jan 30, 2024, 01:16 PM • Last activity: Jan 31, 2024, 06:35 PM
0 votes
1 answers
915 views
Error handling - stored procedure nested in another stored procedure
I've got a stored procedure that call another stored procedure. And i sometime get an error : System.Data.SqlClient.SqlError: The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION. At the advise of my teammate I plan to implement an error handling in the Try Catch that deals with thi...
I've got a stored procedure that call another stored procedure. And i sometime get an error : System.Data.SqlClient.SqlError: The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION. At the advise of my teammate I plan to implement an error handling in the Try Catch that deals with this problem for both the stored procedure. Here is the Catch:
BEGIN CATCH
		IF @@TRANCOUNT = 1 -- if this is the last tranasction - roll it back and close the transaction 
		ROLLBACK;

		IF @@TRANCOUNT > 1 -- if this is not the last tranasction - commit it and return to the previous transaction 
		COMMIT;

		THROW; -- in any case, throw the original error

	END CATCH
i understand it deals with transaction that isn't closed if it's a nested procedure that way it can rollback and commit. and i try to understand what happens in each case: 1. Main procedure running failed before running the nested procedure - 2. Main procedure running failed after running the nested procedure that succeeded - 3. Main procedure running and there is a failure in the nested procedure - here what happens : 1. catch on
IF @@TRANCOUNT = 1 -- if this is the last tranasction - roll it back and close the transaction 
		ROLLBACK;
and rollback 2. what happens for this case? is it this case IF @@@@TRANCOUNT > 1 and if so what happens for the already nested transaction that was commited? 3. what happens for this case? it this case IF @@@@TRANCOUNT > 1 and all the transactions are rollbacked. is my logic for 2 and 3 correct? and is this the right error handling for nested transactions in stored procedure?
dexon (65 rep)
Jan 30, 2024, 01:01 PM • Last activity: Jan 30, 2024, 06:26 PM
3 votes
3 answers
2404 views
Catching two error messages/Throw into table
My goal is to catch errors from backup jobs into monitoring table. The problem is, that there are cases that backup statement returns more than one error, so ERROR_MESSAGE() is not enough: > Msg 3201, Level 16, State 1, Line 1 Cannot open backup device '...' > Operating system error 3(The system can...
My goal is to catch errors from backup jobs into monitoring table. The problem is, that there are cases that backup statement returns more than one error, so ERROR_MESSAGE() is not enough: > Msg 3201, Level 16, State 1, Line 1 Cannot open backup device '...' > Operating system error 3(The system cannot find the path specified.). > > Msg 3013, Level 16, State 1, Line 1 BACKUP DATABASE is terminating > abnormally. I can use throw to catch both messages, but is there an easy way to insert throw output into table or overcome this problem in another way?
Michael Cherevko (742 rep)
May 22, 2016, 05:51 AM • Last activity: Dec 28, 2023, 09:34 PM
Showing page 1 of 20 total questions