SQL Server – Include NULL using UNPIVOT

To preserve NULLs, use CROSS JOIN … CASE: select a.ID, b.column_name , column_value = case b.column_name when ‘col1’ then a.col1 when ‘col2’ then a.col2 when ‘col3’ then a.col3 when ‘col4’ then a.col4 end from ( select ID, col1, col2, col3, col4 from table1 ) a cross join ( select ‘col1’ union all select ‘col2’ union … Read more

How do I use T-SQL’s Exists keyword?

To answer your question about using the EXISTS keyword, here is an example query that uses an EXISTS predicate, based on the query as currently given in your question. SELECT t.* FROM tblTransaction t WHERE EXISTS ( SELECT 1 FROM tblTenantTransCode ttc JOIN tblCheckbookCode cc ON (cc.ID = ttc.CheckbookCode AND cc.Description=’Rent Income’) WHERE ttc.ID = … Read more

SELECT with a Replace()

Don’t use the alias (P) in your WHERE clause directly. You can either use the same REPLACE logic again in the WHERE clause: SELECT Replace(Postcode, ‘ ‘, ”) AS P FROM Contacts WHERE Replace(Postcode, ‘ ‘, ”) LIKE ‘NW101%’ Or use an aliased sub query as described in Nick’s answers.

SQL Current month/ year question

In SQL Server you can use YEAR, MONTH and DAY instead of DATEPART. (at least in SQL Server 2005/2008, I’m not sure about SQL Server 2000 and older) I prefer using these “short forms” because to me, YEAR(getdate()) is shorter to type and better to read than DATEPART(yyyy, getdate()). So you could also query your … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)