Most recent record in a left join

Try this: SELECT a.State, count(c.CustomerID) FROM Product p INNER JOIN Customer c ON c.CustomerID = p.CustomerID LEFT JOIN Address a ON a.CustomerID = c.CustomerID AND a.AddressID = ( SELECT MAX(AddressID) FROM Address z WHERE z.CustomerID = a.CustomerID ) WHERE p.ProductID = 101 GROUP BY a.State

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at the DateDiff() function. — Syntax — DATEDIFF ( datepart , startdate , enddate ) — Example usage SELECT DATEDIFF(DAY, GETDATE(), GETDATE() + 1) AS DayDiff SELECT DATEDIFF(MINUTE, GETDATE(), GETDATE() + 1) AS MinuteDiff SELECT DATEDIFF(SECOND, GETDATE(), GETDATE() + 1) AS SecondDiff SELECT DATEDIFF(WEEK, GETDATE(), GETDATE() + 1) AS WeekDiff SELECT DATEDIFF(HOUR, … Read more

Find non-ASCII characters in varchar columns using SQL Server

Here is a solution for the single column search using PATINDEX. It also displays the StartPosition, InvalidCharacter and ASCII code. select line, patindex(‘%[^ !-~]%’ COLLATE Latin1_General_BIN,Line) as [Position], substring(line,patindex(‘%[^ !-~]%’ COLLATE Latin1_General_BIN,Line),1) as [InvalidCharacter], ascii(substring(line,patindex(‘%[^ !-~]%’ COLLATE Latin1_General_BIN,Line),1)) as [ASCIICode] from staging.APARMRE1 where patindex(‘%[^ !-~]%’ COLLATE Latin1_General_BIN,Line) >0

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008: INSERT INTO [MyDB].[dbo].[MyTable] ([FieldID] ,[Description]) VALUES (1000,N’test’),(1001,N’test2′) For SQL Server 2005, you will have to use multiple INSERT statements: INSERT INTO [MyDB].[dbo].[MyTable] ([FieldID] ,[Description]) VALUES (1000,N’test’) INSERT INTO [MyDB].[dbo].[MyTable] ([FieldID] ,[Description]) VALUES (1001,N’test2′) One other option is to use UNION ALL: INSERT INTO [MyDB].[dbo].[MyTable] … Read more