Referring to a Column Alias in a WHERE Clause

SELECT logcount, logUserID, maxlogtm, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff FROM statslogsummary WHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120) Normally you can’t refer to field aliases in the WHERE clause. (Think of it as the entire SELECT including aliases, is applied after the WHERE clause.) But, as mentioned in other answers, you can force SQL to … Read more

How to update two tables in one statement in SQL Server 2005?

You can’t update multiple tables in one statement, however, you can use a transaction to make sure that two UPDATE statements are treated atomically. You can also batch them to avoid a round trip. BEGIN TRANSACTION; UPDATE Table1 SET Table1.LastName=”DR. XXXXXX” FROM Table1 T1, Table2 T2 WHERE T1.id = T2.id and T1.id = ‘011008’; UPDATE … Read more

Turn off constraints temporarily (MS SQL)

— Disable the constraints on a table called tableName: ALTER TABLE tableName NOCHECK CONSTRAINT ALL — Re-enable the constraints on a table called tableName: ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL ——————————————————— — Disable constraints for all tables in the database: EXEC sp_msforeachtable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’ — Re-enable constraints for all … Read more