Temporarily disable all foreign key constraints

To disable foreign key constraints: DECLARE @sql nvarchar(max) = N”; ;WITH x AS ( SELECT DISTINCT obj = QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id)) + ‘.’ + QUOTENAME(OBJECT_NAME(parent_object_id)) FROM sys.foreign_keys ) SELECT @sql += N’ALTER TABLE ‘ + obj + N’ NOCHECK CONSTRAINT ALL; ‘ FROM x; EXEC sys.sp_executesql @sql; To re-enable: DECLARE @sql nvarchar(max) = N”; ;WITH x AS … Read more

SQL Server Group by Count of DateTime Per Hour?

How about this? Assuming SQL Server 2008: SELECT CAST(StartDate as date) AS ForDate, DATEPART(hour,StartDate) AS OnHour, COUNT(*) AS Totals FROM #Events GROUP BY CAST(StartDate as date), DATEPART(hour,StartDate) For pre-2008: SELECT DATEADD(day,datediff(day,0,StartDate),0) AS ForDate, DATEPART(hour,StartDate) AS OnHour, COUNT(*) AS Totals FROM #Events GROUP BY CAST(StartDate as date), DATEPART(hour,StartDate) This results in : ForDate | OnHour | … Read more

Which join syntax is better?

Well, “better” is subjective. There is some style here. But I’ll address your questions directly. Both perform the same Both are ANSI-compliant. The problem with the first example is that it is very easy to inadvertently derive the cross product (since it is easier to leave out join criteria) it also becomes difficult to debug … Read more

Joining multiple tables returns NULL value

That is because null on either side of the addition operator will yield a result of null. You can use ISNULL(LiabilityPremium, 0) Example: ISNULL(l.LiabilityPremium,0) + ISNULL(h.LiabilityPremium,0) as LiabilityPremium or you can use COALESCE instead of ISNULL. COALESCE(l.LiabilityPremium,0) + COALESCE(h.LiabilityPremium,0) as LiabilityPremium Edit I am not sure if this is coincidence with this small data set … Read more