Skip to content

Tag: tsql

How do I show all records when one field is null in SQL?

I have my code but the @NAME is an optional field for searching. If the @NAME is blank or NULL, it should show all records. How do I approach this? Thanks! Answer There are some ways to do it the easy way. I would do something like this. You can use the Function ISNULL to handle blank or NULL. With

Check if procedure exists in any database SQL Server

I’d like to know if there is any way to search for a procedure in all the databases of a server (there are only SQL Server databases on that server). So far I’ve only found how to find a stored procedure in a certain database with Object_id(), but it would take too long for me to manually search e…

How to group by two columns in different CASE clauses

I have a query that’s giving me the results I want, but for each item with a given ID_UNIDAD_EXPERIMENTAL there are two rows, one with column “Alt” with a value and column “Dap” with null, and the other one with “Alt” null and “Dap” with a value. My questi…

Arithmetic Overflow Error if Varchar is over 999, WHY?

I discovered a weird issue in my database, I was able to fix it, but I do not understand WHY the error occurred in the first place. I’m using Microsoft SQL Server 2017. The following code returns an Arithmetic Overflow error: Returns Error: Arithmetic overflow error converting varchar to data type numer…

Delete all but the newest with specific filename

I migrated a file logger to log to the database instead of to disk. This caused many duplicates in the database, whereas on disk the file would have just gotten overwritten. I want to delete all the “not newest” rows given a specific filename, what SQL would do this given the following table: The …

Accurate DateDiff

I have 2 time fields in SQL. I want to calculate the difference between start time and end time in hours. From 7 AM in the morning to 7:30 PM it would be 12.5 hours but the datediff function returns 12 hours because it returns an integer. I also tried converting it to seconds: All of these return 12 hours