Need a datetime column in SQL Server that automatically updates when the record is modified

SQL Server doesn’t have a way to define a default value for UPDATE. So you need to add a column with default value for inserting: ADD modstamp DATETIME2 NULL DEFAULT GETDATE() And add a trigger on that table: CREATE TRIGGER tgr_modstamp ON **TABLENAME** AFTER UPDATE AS UPDATE **TABLENAME** SET ModStamp = GETDATE() WHERE **ID** IN … Read more

Possible to store value of one select column and use it for the next one?

You need CROSS APPLY here, it can refer to outer references, no annoying subqueries or CTEs needed: select col1, col2 from table1 as outer_table — can also have multi-row values cross apply (values (complex_expression_1) ) as v1 (col1) cross apply (values (expression_referring_to_col1) ) as v2 (col2) — alternate syntax, select without from returns a single … Read more

Why is 1899-12-30 the zero date in Access / SQL Server instead of 12/31?

Maintaining compatibility with Lotus 1-2-3 back in the day, which had a bug in that it thought the year 1900 was a leap year (or pretended?). The explanation is too long to quote, but for the sake of curiosity, here are some snippets. http://blogs.msdn.com/b/ericlippert/archive/2003/09/16/53013.aspx http://www.joelonsoftware.com/items/2006/06/16.html 1900 wasn’t a leap year. “It’s a bug in Excel!” … Read more

SQL Server Random Sort

This is a duplicate of SO# 19412. Here’s the answer I gave there: select top 1 * from mytable order by newid() In SQL Server 2005 and up, you can use TABLESAMPLE to get a random sample that’s repeatable: SELECT FirstName, LastName FROM Contact TABLESAMPLE (1 ROWS) ;

Do I really need to use “SET XACT_ABORT ON”?

Remember that there are errors that TRY-CATCH will not capture with or without XACT_ABORT. However, SET XACT_ABORT ON does not affect trapping of errors. It does guarantee that any transaction is rolled back / doomed though. When “OFF”, then you still have the choice of commit or rollback (subject to xact_state). This is the main … Read more