March 2, 2016

Find column in database

This script finds all tables with a specific column in the database:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_idAS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c 
ON t.OBJECT_ID c.OBJECT_ID
WHERE c.name LIKE '%ClientID%'
ORDER BY schema_nametable_name;

March 1, 2016

CTE and Pivot

/* Pivot to display queues horizontally */

WITH Validation AS
(
select top 100 percent
UserName, QueueName, EndDate, Count(DocumentID) AS 'QueueCount'
From ValidationGroup
Group by UserName, QueueName, EndDate
Order by UserName, QueueName
)
select * from (
select top 100 percent
UserName, QueueName, EndDate, isnull(QueueCount,0) AS 'QueueCount'
From ValidationGroup
Group by UserName, QueueName, EndDate, QueueCount
Order by UserName
) src
pivot
(
Sum(QueueCount)
for QueueName in ([Incoming,Validation,Appeal,Pending)
) p;