Wednesday, July 23, 2014

How to Write Dynamic SQL

Nice article explaining how to write Dynamic SQL:


-- Declare variable to hold dynamic TSQL code DECLARE @CMD nvarchar(1000); -- Declare name of table to read DECLARE @Table nvarchar(125); SET @Table = 'AdventureWorks2012.Sales.SalesOrderDetail'; -- Build dynamic TSQL Statement SET @CMD = 'SELECT TOP 10 * FROM ' + @Table; --Execute dynamic TSQL Statement EXECUTE (@CMD);


Monday, July 21, 2014

HAVING (UpdatedDate = MAX(UpdatedDate))

Getting 1 ID for each of the latest Updated records:

SELECT        ID, UpdatedDate
FROM            SomeTable
GROUP BY  ID, UpdatedDate
HAVING        (UpdatedDate = MAX(UpdatedDate))