T-SQL Conditional Order By

CASE is an expression that returns a value. It is not for control-of-flow, like IF. And you can’t use IF within a query. Unfortunately, there are some limitations with CASE expressions that make it cumbersome to do what you want. For example, all of the branches in a CASE expression must return the same type, … Read more

How do you drop a default value or similar constraint in T-SQL?

You can use this code to do it automatically: DECLARE @tableName VARCHAR(MAX) = ‘<MYTABLENAME>’ DECLARE @columnName VARCHAR(MAX) = ‘<MYCOLUMNAME>’ DECLARE @ConstraintName nvarchar(200) SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID(@tableName) AND PARENT_COLUMN_ID = ( SELECT column_id FROM sys.columns WHERE NAME = @columnName AND object_id = OBJECT_ID(@tableName)) IF @ConstraintName IS NOT NULL EXEC(‘ALTER TABLE … Read more

How to calculate difference in hours (decimal) between two dates in SQL Server?

DATEDIFF(hour, start_date, end_date) will give you the number of hour boundaries crossed between start_date and end_date. If you need the number of fractional hours, you can use DATEDIFF at a higher resolution and divide the result: DATEDIFF(second, start_date, end_date) / 3600.0 The documentation for DATEDIFF is available on MSDN: http://msdn.microsoft.com/en-us/library/ms189794%28SQL.105%29.aspx