SQL Server error message truncated - sql-server

This is not an error message about truncation. Rather, the error message itself (from SSMS) appears to have been truncated. Any idea what it was trying to tell me here? Is there a way to recover the full error message?
Msg 203, Level 16, State 2, Line 80
The name 'SELECT
SUM(CASE WHEN #actual_types.typ = 'AA' THEN #actual_types.qty ELSE 0 END) AS 'AA_Qty',
SUM(CASE WHEN #actual_types.typ = 'AB' THEN #actual_types.qty ELSE 0 END) AS 'AB_Qty',
SUM(CASE WHEN #actual_types.typ = 'AC' THEN #actual_types.qty ELSE 0 END) AS 'AC_Qty',
SUM(CASE WHEN #actual_types.typ = 'BA' THEN #actual_types.qty ELSE 0 END) AS 'BA_Qty',
SUM(CASE WHEN #actual_types.typ...
I'm using SSMS 2016, connected to a SQL 2000 server. For context - I was trying to create a more generic version of one of my current scripts (works fine against production data), using temp tables and sample data, to save as a reference in case I should need something similar in the future.
This was the code responsible for the error:
CREATE TABLE #possible_types
(typ varchar(2))
CREATE TABLE #actual_types
(typ varchar(2),
dt smalldatetime,
qty int)
INSERT #possible_types
SELECT 'AA'
UNION SELECT 'AB'
UNION SELECT 'AC'
UNION SELECT 'BA'
UNION SELECT 'BB'
UNION SELECT 'BC'
INSERT #actual_types
SELECT 'AA', '2015-01-01', 123
UNION SELECT 'AA', '2016-01-01', 321
UNION SELECT 'AA', '2017-01-01', 222
UNION SELECT 'BA', '2016-01-01', 777
UNION SELECT 'BC', '2017-01-01', 456
DECLARE #qry varchar(8000)
SELECT #qry = 'SELECT' + CHAR(13)
SELECT #qry = #qry + s.sql_gen
FROM
(SELECT DISTINCT 'SUM(CASE WHEN #actual_types.typ = '''+ typ + ''' THEN #actual_types.qty ELSE 0 END) AS ''' + typ + '_Qty'',' + char(13) AS [sql_gen]
FROM #possible_types) s
SELECT #qry = LEFT(#qry, LEN(#qry) - 2) -- gets rid of last comma and carriage return
SELECT #qry = #qry + '
FROM #actual_types
WHERE #actual_types.dt >= ''2017-01-01''
'
--PRINT #qry
EXEC #qry;
DROP TABLE #possible_types
DROP TABLE #actual_types

Error messages in sql server are stored in sys.messages. You can query the messages table using the information provided.
select * from sys.messages
where message_id = 203
and language_id = 1033 --1033 is English (assumed you can read English)
This returns "The name '%.*ls' is not a valid identifier."
You obviously have something else wonky in your code. Can you share your query and we can probably help determine the actual cause of the issue.

I had the same error. Now it works for me.
I removed the ' for the name of the fields _Qty. (Actually it's not necessary for made your query working).
Moreover I edited:
DECLARE #qry nvarchar(4000)
and
EXECUTE sp_executesql #qry;
Full code edited:
CREATE TABLE #possible_types
(typ varchar(2))
CREATE TABLE #actual_types
(typ varchar(2),
dt smalldatetime,
qty int)
INSERT #possible_types
SELECT 'AA'
UNION SELECT 'AB'
UNION SELECT 'AC'
UNION SELECT 'BA'
UNION SELECT 'BB'
UNION SELECT 'BC'
INSERT #actual_types
SELECT 'AA', '2015-01-01', 123
UNION SELECT 'AA', '2016-01-01', 321
UNION SELECT 'AA', '2017-01-01', 222
UNION SELECT 'BA', '2016-01-01', 777
UNION SELECT 'BC', '2017-01-01', 456
DECLARE #qry nvarchar(4000)
SELECT #qry = 'SELECT' + CHAR(13)
SELECT #qry = #qry + s.sql_gen
FROM
(SELECT DISTINCT 'SUM(CASE WHEN #actual_types.typ = '''+ typ + ''' THEN #actual_types.qty ELSE 0 END) AS ' + typ + '_Qty,' + char(13) AS [sql_gen]
FROM #possible_types) s
SELECT #qry = LEFT(#qry, LEN(#qry) - 2) -- gets rid of last comma and carriage return
SELECT #qry = #qry + '
FROM #actual_types
WHERE dt >= ''2017-01-01''
'
PRINT #qry
EXECUTE sp_executesql #qry;
DROP TABLE #possible_types
DROP TABLE #actual_types

Related

Union on Dynamic (Loop) SQL Server

with the below loop script, I am creating tables for every period. What I need is that I would like to union all these multiple tables into one single table within the same script. Can anyone help me do that?
DECLARE #Interval_List as TABLE (index_1 int, Interval VARCHAR(50), Interval_2 VARCHAR(50), From_date date, To_date date)
INSERT INTO #Interval_List VALUES (1, '2021_Q3', '2021 Q3', '2021-07-01', '2021-09-30')
INSERT INTO #Interval_List VALUES (2, '2021_Q4', '2021 Q4', '2021-10-01', '2021-12-31')
INSERT INTO #Interval_List VALUES (3, '2021_H2', '2021 H2', '2021-07-01', '2021-12-31')
INSERT INTO #Interval_List VALUES (4, '2021', '2021', '2021-07-01', '2021-12-31')
DECLARE #StartDate AS DATE
DECLARE #EndDate AS DATE
DECLARE #CurrentDate AS DATE
DECLARE #index_first int
declare #index_last int
declare #interval VARCHAR(50)
declare #interval_2 VARCHAR(50)
declare #issue_table nvarchar(max)
declare #service_table nvarchar(max)
SELECT #index_first = min(index_1), #index_last = max(index_1) FROM #Interval_List
SET #CurrentDate = #StartDate
SET #issue_table = 'dbo.table1'
SET #service_table = 'dbo.table2'
WHILE (#index_first <= #index_last)
BEGIN
SELECT #StartDate = From_date, #EndDate = To_date, #interval = Interval, #interval_2 = Interval_2 FROM #Interval_List where index_1 = #index_first
IF OBJECT_ID(#issue_table) IS NULL
BEGIN
RAISERROR('Bad object!', 11, 1);
RETURN;
END
declare #query nvarchar(max);
set #query =
N'
SELECT
A.SERVICE,
A.Service_Group,
A.Portfolio,
Interval,
SUM(Metric_1_Dividend_C_New) AS Metric_1_Dividend_C_New
'
+ N'into dbo.METRIC_1_' + #interval
+
N'
FROM
(
SELECT
ISSUE_CREATION_DATE,
ISSUE_ID,
SERVICE,
SERVICE_GROUP,
PORTFOLIO,
#Interval_2 as Interval,
AVG(Metric_No_1_Dividend) AS Metric_1_Dividend_C_New
'
+ N' from ' + #issue_table +
N' where PROJECT IS NOT NULL
AND cast(FORMAT(ISSUE_CREATION_DATE, ''yyyyMMdd'') as varchar(30)) >= cast(FORMAT(#StartDate, ''yyyyMMdd'') as varchar(30))
AND cast(FORMAT(ISSUE_CREATION_DATE, ''yyyyMMdd'') as varchar(30)) <= cast(FORMAT(#EndDate, ''yyyyMMdd'') as varchar(30))
GROUP BY ISSUE_CREATION_DATE, ISSUE_ID,SERVICE,SERVICE_GROUP,PORTFOLIO
) A
GROUP BY SERVICE,Service_Group,Portfolio,Interval
'
exec sys.sp_executesql #query,
N'#StartDate date, #EndDate date, #Interval_2 VARCHAR(50)',
#StartDate, #EndDate, #Interval_2;
SET #index_first = #index_first + 1;
END
;
Before you continue, please make sure that you read about table partitioning and creating a view for your unions, because, intuitively the problem you describe sounds like these. If neither partitioning, nor views are good for you, then read the sections below:
How can I get tables by name
SELECT [name]
FROM sys.tables
WHERE [name] LIKE '%somepattern%'
How to generate a command:
SELECT CONCAT('INSERT INTO ', [name], '(col1, col2, col3) values(', value1, ', ', value2, ', ', value3, ')')
FROM sys.tables
WHERE [name] LIKE '%somepattern%'
How to concatenate rows
You can use STRING_AGG(yourstring, 'separator'), like:
SELECT STRING_AGG(CONCAT('INSERT INTO ', [name], '(col1, col2, col3) values(', value1, ', ', value2, ', ', value3, ')'), ' UNION ')
FROM sys.tables
WHERE [name] LIKE '%somepattern%'

How to pivot columns in SQL Server

I'm new to SQL Server and I am trying to pivot rows into columns
select SalesOrExpense, store_no, total
from myTable
SalesOrExpense Store_No total ($)
-------------------------------------
Expense 22 100
Sales 22 400
to look like this
Store_No Expense Sales
---------------------------------
22 100 400
Could someone help point me in the right direction?
Thanks
We can even do it by executing dynamic sql query..
Query
declare #sql as varchar(max);
select #sql = stuff((
select ', sum(case [SalesOrExpense] when ' + char(39) +
[SalesOrExpense] + char(39) +
' then [total] else 0 end) as [' + [SalesOrExpense] + ']'
from [your_table_name]
for xml path('')
)
, 1, 2, ''
);
select #sql = 'select [Store_No], ' + #sql +
' from [your_table_name] group by [Store_No];';
exec(#sql);
CREATE TABLE #Table1
([SalesOrExpense] varchar(7), [Store_No] int, [total] int)
;
INSERT INTO #Table1
([SalesOrExpense], [Store_No], [total])
VALUES
('Expense', 22, 100),
('Sales', 22, 400)
select *
from
(
select *
from #Table1
) src
pivot
(
max(total)
for SalesOrExpense in ([Expense], [Sales])
) piv;
CREATE TABLE #Table1
([SalesOrExpense] varchar(7), [Store_No] int, [total] int);
INSERT INTO #Table1
([SalesOrExpense], [Store_No], [total])
VALUES
('Expense', 22, 100),
('Sales', 22, 400);
SELECT Store_No,
SUM(CASE WHEN SalesOrExpense='Expense' THEN TOTAL END) AS Expense,
SUM(CASE WHEN SalesOrExpense='Sales' THEN TOTAL END) AS Sales
FROM #table1 GROUP BY Store_No;
OUTPUT:-
-------------------------
Store_No | Expense |Sales
---------------------------
22 100 400

Formatting SQL Server Query Output

I like to get the SQL Server query output in the following way. Currently my output is:
Class | Student ID | Student Name
------+------------+---------------
121 S1 Test 1
121 S2 Test 2
500 S22 Test a
500 S23 Test b
But I want the data output in the following way -
Class: 121
--------------------------------
Student ID | Student Name
-----------+---------------
S1 Test 1
S2 Test 2
Class: 500
--------------------------------
Student ID | Student Name
-----------+---------------
S22 Test a
S23 Test b
Could someone help me how can I achieve these?
Thanks
While I would agree SQL isn't the place to do your formatting.... sometimes you get stuck....
This Code
select '121' as Class, 'S1 ' as [Student ID], 'Test 1' as [Student Name] into #test
union select '121', 'S2 ', 'Test 2'
union select '500', 'S22 ', 'Test a'
union select '500', 'S23 ', 'Test b'
;
WITH class
AS (
SELECT DISTINCT class
FROM #test
)
,student
AS (
SELECT class
,(
SELECT STUFF((
SELECT CHAR(13) + t.[Student ID] + space(len('Student ID | ') - len(t.[Student ID])) + [Student Name]
FROM #Test t
WHERE t.[class] = class.[class]
FOR XML PATH('')
,type
).value('.[1]', 'nvarchar(max)'), 1, 1, '')
) AS info
FROM class
)
,theoutput
AS (
SELECT 'Class: ' + class + CHAR(13) + '------------------------' + CHAR(13) + 'Student ID | Student Name' + CHAR(13) + info + CHAR(13) + CHAR(13) AS txt
FROM student c
)
SELECT STUFF((
SELECT CHAR(13) + txt
FROM theoutput
FOR XML PATH('')
,type
).value('.[1]', 'nvarchar(max)'), 1, 1, '')
Will Produce
Class: 121
------------------------
Student ID | Student Name
S1 Test 1
S2 Test 2
Class: 500
------------------------
Student ID | Student Name
S22 Test a
S23 Test b
By using While loop we can get the Desired result Created sample data
IF OBJECT_ID('Tempdb..#TEMP') IS NOT NULL
Drop table #TEMP
;With cte(Class, StudentID, StudentName)
AS
(
SELECT 121,'S1' ,'Test 1' UNION ALL
SELECT 121,'S2' ,'Test 2' UNION ALL
SELECT 500,'S22','Test a' UNION ALL
SELECT 500,'S23','Test b'
)
SELECT * INTO #TEMP FROM CTe
SET NOCOUNT ON
DECLARE #CLassCOUnt INT
,#minID INT
,#maxid INT
,#Sql NVARCHAR(max)
,#SelectQuery INT
DECLARE #Table TABLE (
ID INT IDENTITY
,CLass INT
)
INSERT INTO #Table (CLass)
SELECT DISTINCT Class
FROM #TEMP
SELECT #minID = min(Id)
FROM #Table
SELECT #maxid = MAX(Id)
FROM #Table
WHILE (#minID <= #maxid)
BEGIN
SELECT #SelectQuery = Class
FROM #Table
WHERE ID = #minID
SELECT #Sql = 'SELECT Class, StudentID, StudentName FROM #TEMP WHERE Class=' + CAST(#SelectQuery AS VARCHAR)
PRINT 'Result Of Class:'+ CAST(#SelectQuery AS VARCHAR)+CHAR(13)+CHAR(10)+'------------------------'
PRINT #Sql
EXEC (#Sql)
SET #minID = #minID + 1
END
SET NOCOUNT OFF

Counting the number of columns greater than 0 for each row in SQL Server 2012

I have a table with more than 150 columns. is there any way to dynamically count columns greater than 0 for each customer.
table view is like :
CustomerID (SomeColumns) Column1 Column2 ------------------ Column150
1 ----- 0 12 0 33 0 18 97
2 ----- 1 0 54 0 72 0 0
.
.
.
This table has 500K rows. values of column1 to column150 are either 0 or not. how can I count the number of columns greater than 0 ?
Query:
Update Table
set NumOfColumnsGreaterThanZero = (select Sum(case when Column1 to Column150 >0 then 1 else 0 end)
You can create a dynamic SQL based on sys.columns, something like:
declare #columns varchar(8000), #sql varchar(8000)
set #columns = ''
select #columns = #columns + 'case when [' + name + '] > 0 then 1 else 0 end+'
from sys.columns
where
object_id = object_id('TABLENAME') and
name not in ('not','wanted','columns') and
user_type_id in (select user_type_id from sys.types where name = 'int')
set #sql = 'select CustomerId, ' + #columns + '0 as VALUE from TABLENAME'
exec (#sql)
There is of course a risk with this approach that adding new columns to the table might cause unwanted results.
I doubt you have a valid reason for having 150 columns. However here is how you could count the values that are not 0 using Pivot:
DECLARE #table TABLE(customer_id int, col1 int, col2 int,
col3 int, col4 int, col5 int);
INSERT INTO #table
VALUES(1, 1, 2, 3, 4, 5) ,(2, 0, 2, 0, 4, 5)
SELECT count(CASE WHEN columns <> 0 THEN 1 END), customer_id
FROM #table as p
UNPIVOT
(columns FOR Seq IN
([col1], [col2], [col3], [col4], [col5]) ) AS unpvt
GROUP BY customer_id
Result:
5 1
3 2
If you want to select the columns dynamically:
CREATE TABLE
test_table(customer_id int, col1 int, col2 int,
col3 int, col4 int, col5 int);
INSERT INTO test_table
VALUES(1, 1, 2, 3, 4, 5) ,(2, 0, 2, 0, 4, 5) ;
DECLARE #columnnames varchar(max)
SELECT #columnnames = coalesce(#columnnames + ',['+ column_name + ']' , '['+ column_name + ']' )
FROM INFORMATION_SCHEMA.Columns
WHERE
table_name = 'test_table' and
column_name like 'col[0-9]%' and
table_schema = 'dbo'
ORDER BY column_name
DECLARE #sql varchar(max) =
'SELECT count(CASE WHEN columns <> 0 THEN 1 END), customer_id
FROM test_table as p
UNPIVOT
(columns FOR Seq IN
('+#columnnames+') ) AS unpvt
GROUP BY customer_id'
EXEC (#sql)
This is a basic example using 3 columns on a temporary table. You could adapt that for your structure using Dynamic SQL.
Sample data:
CREATE TABLE #Customers
(
CustomerID INT
, SomeColumn VARCHAR(100)
, Column1 INT
, Column2 INT
, Column3 INT
);
INSERT INTO #Customers
(CustomerID, SomeColumn, Column1, Column2, Column3)
VALUES
(1, 'aaa', 1, 0, 2)
, (2, 'bbb', 0, 0, 3)
, (3, 'ccc', 0, 0, 0)
Actual query:
SELECT CustomerID, SomeColumn, IIF(Column1 > 0, 1, 0) + IIF(Column2 > 0, 1, 0) + IIF(Column3 > 0, 1, 0) AS T
FROM #Customers
Results look like this:
CustomerID SomeColumn T
1 aaa 2
2 bbb 1
3 ccc 0
to avoid i misunderstand your question, i try to create sample table and data, basically what i understand from your questions is, each of the columns are integer type, whenever the record is more then 0 then set to 1, else 0; this is good if you able to provide sample data and expected output. :)
CREATE TABLE tblTEST
(
COLUMN1 INT,
COLUMN2 INT,
COLUMN3 INT,
COLUMN4 INT,
COLUMN5 INT
)
INSERT INTO tblTEST
SELECT 1,0,5,12,6
UNION ALL
SELECT 1,10,0,12,6
UNION ALL
SELECT 1,30,5,0,6
DECLARE #ColumnName NVARCHAR(MAX) = ''
DECLARE #Table_Name NVARCHAR(1000) = 'TBLTEST'
DECLARE #Query NVARCHAR(MAX) = ''
DECLARE #nStart INT = 1
DECLARE #nLast INt = (SELECT COUNT(1) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #Table_Name )
WHILE #nStart <=#nLast
BEGIN
SET #ColumnName = #ColumnName + ' CASE WHEN '+ (SELECT COLUMN_NAME FROM(SELECT COLUMN_NAME,ROW_NUMBER() OVER(ORDER BY COLUMN_NAME) RN FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #Table_Name) T1 WHERE RN=#nStart) + ' >0 THEN 1 ELSE 0 END '+ (SELECT COLUMN_NAME FROM(SELECT COLUMN_NAME,ROW_NUMBER() OVER(ORDER BY COLUMN_NAME) RN FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #Table_Name) T1 WHERE RN=#nStart) + ','
SET #nStart = #nStart + 1
END
SET #ColumnName = SUBSTRING(#ColumnName,1,LEN(#ColumnName)-1)
SET #Query = 'SELECT ' + #ColumnName + ' FROM ' + #Table_Name
EXECUTE SP_EXECUTESQL #Query
Another option is to use dynamic sql and while cycle
Sample data
-- Populate some sample data
IF OBJECT_ID('tempdb..#T','U') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T
(Column1 INT, Column2 INT, Column3 INT, Column4 INT, Column5 INT);
INSERT INTO #T VALUES
(0,0,0,1,0),
(0,1,0,1,0),
(1,0,0,2,0),
(1,0,0,0,1);
Dynamic SQL with while cycle
DECLARE #ResultTable TABLE (HasZeroValue TINYINT);
-- Number of columns to search for zero values
DECLARE #ColumnsCount INT = 5;
-- Dynamic sql statement
DECLARE #SQL NVARCHAR(MAX);
DECLARE #i INT = 1;
WHILE #i <= #ColumnsCount
BEGIN
SET #SQL = 'SELECT CASE COUNT(*) WHEN 0 THEN 0 ELSE 1 END FROM #T WHERE Column' + CAST(#i AS VARCHAR) + ' > 0;';
INSERT #ResultTable
EXEC sp_executesql #SQL;
SET #i = #i + 1;
END
SELECT SUM(HasZeroValue) FROM #ResultTable;

Looking for more efficient way to select max RowUpdateDateTime column across multiple tables

Each row in each table of my database has a RowUpdateDateTime column, which is the latest time that particular row was updated or inserted. I've also got between 1 and 7 distinct sources of data coming into each table; some have 1, some have 7.
Basically, I'm trying to loop through these tables and find the most recent RowUpdateDateTime for each of these sources, where applicable, for each of these tables. Here's the really long query that I and a colleague wrote to do this. It's functional, but I suspect could be re-written.
IF OBJECT_ID('tempdb..#SourceID') IS NOT NULL
BEGIN
DROP TABLE #SourceID
END
IF OBJECT_ID('tempdb..#Tables') IS NOT NULL
BEGIN
DROP TABLE #Tables
END
IF OBJECT_ID('tempdb..#UpdateCount') IS NOT NULL
BEGIN
DROP TABLE #UpdateCount
END
GO
CREATE TABLE #SourceID
(
SourceID varchar(4),
CounterID int
)
INSERT INTO #SourceID (SourceID,CounterID)
SELECT 'ZEND',1
UNION ALL
SELECT 'ABC',2
UNION ALL
SELECT 'DEF',3
UNION ALL
SELECT 'GHI',4
UNION ALL
SELECT 'JKL',5
UNION ALL
SELECT 'MNO',6
UNION ALL
SELECT 'PQR',7
UNION ALL
SELECT 'STU',8
GO
CREATE TABLE #Tables
(
Name varchar(100),
CounterID int
)
INSERT INTO #Tables (Name,CounterID)
SELECT 'livendb..Table1',1
UNION ALL
SELECT 'livendb..Table2',2
UNION ALL
SELECT 'livendb..Table3',3
UNION ALL
SELECT 'livendb..Table4',4
UNION ALL
SELECT 'livendb..Table5',5
UNION ALL
SELECT 'livendb..Table6',6
UNION ALL
SELECT 'livendb..Table7',7
UNION ALL
SELECT 'livefdb..Table8',8
UNION ALL
SELECT 'livefdb..Table9',9
UNION ALL
SELECT 'livefdb..Table10',10
UNION ALL
SELECT 'livefdb..Table11',11
UNION ALL
SELECT 'livefdb..Table12',12
UNION ALL
SELECT 'livefdb..Table13',13
GO
Declare #counter varchar(10)
Declare #tablename varchar(100)
Declare #query varchar(1100)
Declare #sourceid varchar(4)
Declare #sourcecounter varchar(10)
CREATE TABLE #UpdateCount
(
SourceID varchar(3),
TableName Varchar(100),
MaxRowUpdateDateTime datetime,
--TotalRowCount int
)
SET #sourcecounter = (SELECT COUNT(*) FROM #SourceID)
SET #counter = (SELECT COUNT (*) FROM #Tables)
WHILE #sourcecounter >= 0
BEGIN
SET #sourceid = (SELECT SourceID FROM #SourceID WHERE CounterID = (#sourcecounter))
IF #sourceid <> 'ZEND'
BEGIN
WHILE #counter >=0
BEGIN
SET #tablename = (SELECT Name FROM #Tables WHERE CounterID = (#counter))
IF #counter <> 0
BEGIN
SET #query = 'INSERT INTO #UpdateCount (SourceID,TableName,MaxRowUpdateDateTime)
VALUES (
(SELECT SourceID FROM #SourceID WHERE CounterID = '+#sourcecounter+')
,(SELECT Name FROM #Tables WHERE CounterID = '+#counter+')
,(SELECT MAX(RowUpdateDateTime) FROM '+#tablename+' WHERE SourceID =
(SELECT SourceID FROM #SourceID WHERE CounterID = '+#sourcecounter+')))'
EXECUTE (#query)
END
SET #counter = (#counter-1)
END
END
SET #sourcecounter = (#sourcecounter-1)
SET #counter = (SELECT COUNT (*) FROM #Tables)
END
SELECT SourceID
,SUBSTRING(TableName,10,22) as TableName
,MaxRowUpdateDateTime
--,TotalRowCount
FROM #UpdateCount
Where MaxRowUpdateDateTime IS NOT NULL
ORDER BY TableName
DROP TABLE #Tables
DROP TABLE #UpdateCount
DROP TABLE #SourceID
You might be better off (as the code is simpler) following a pattern like this example. It does not answer your entire question (its quite hard to code dynamic SQL with no data - for me at least).
This should give you a good starting point to work from.
USE AdventureWorks2012
GO
DECLARE #Query VARCHAR(MAX) =''
;WITH Tables AS
(
SELECT DISTINCT TABLE_NAME = '[' + TABLE_SCHEMA + ']' + '.' + '[' + TABLE_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'ModifiedDate'
)
SELECT #Query = #Query +
' SELECT SourceTable = '''+ TABLE_NAME + '''
,RecentMod = MAX(ModifiedDate)
FROM ' + TABLE_NAME + ' UNION ALL'
FROM Tables
SET #Query = LEFT(#Query, LEN(#Query) - LEN(' UNION ALL'))
EXEC (#Query)
Producing a result like this;
SourceTable | RecentMod
===========================================================================
[dbo].[AWBuildVersion] | 2012-03-14 00:00:00.000
[dbo].[OLE DB Destination] | 2008-07-31 00:00:00.000
[HumanResources].[Department] | 2002-06-01 00:00:00.000
[HumanResources].[Employee] | 2009-01-26 09:17:08.637
[HumanResources].[EmployeeDepartmentHistory] | 2007-12-15 00:00:00.000
[HumanResources].[EmployeePayHistory] | 2008-07-31 00:00:00.000
[HumanResources].[JobCandidate] | 2008-01-23 18:32:21.313
[HumanResources].[Shift] | 2002-06-01 00:00:00.000
[HumanResources].[vJobCandidate] | 2008-01-23 18:32:21.313
[Person].[Address] | 2008-07-31 00:00:00.000
[Person].[AddressType] | 2002-06-01 00:00:00.000
[Person].[BusinessEntity] | 2012-01-14 13:47:22.467
[Person].[BusinessEntityAddress] | 2008-10-13 11:15:06.967
...

Resources