January 6, 2009 at 1:09 pm
Folks,
Say I have a table with columns, colA, colB, colC and colD and there are 20 rows in my table. I want to write a sort of dynamic script to show me a count of non-null columns.
The result set would look something like
colA 5
colB 20
colC 10
colD 1
This example would show that each row had colb populated in each of the 20 rows.
I know I could write a select that would generate some individual sql statements using syscolumns.name and syscolumns.id and I could then execute each of those statements but is there a way to do this more neatly ?
January 6, 2009 at 1:22 pm
Better would be to use the information schema views.
Keep in mind that sql2005 only show object definitions you are granted to view.
(view definition granted)
Is this what you're looking for ?
SELECT CASE t1.[ORDINAL_POSITION] WHEN 1 THEN 'SELECT ' ELSE ' , ' end
+ ' count( distinct ['+ t1.[COLUMN_NAME] + '] ) as [Count_distinct_' + t1.[COLUMN_NAME] + '_'
+ CASE t1.[ORDINAL_POSITION] WHEN t2.[MAX_ORDINAL_POSITION] THEN ' from [' + t1.[TABLE_SCHEMA] + '].[' + t1.[TABLE_NAME] + '] ;' ELSE ' ' end
FROM [INFORMATION_SCHEMA].[COLUMNS] t1
INNER JOIN
( SELECT [TABLE_NAME], [TABLE_SCHEMA], MAX([ORDINAL_POSITION]) AS MAX_ORDINAL_POSITION
FROM [INFORMATION_SCHEMA].[COLUMNS]
GROUP BY [TABLE_NAME], [TABLE_SCHEMA]
)t2
ON t1.[TABLE_NAME] = t2.[TABLE_NAME]
AND t1.[TABLE_SCHEMA] = t2.[TABLE_SCHEMA]
WHERE t1.[TABLE_NAME] = 'mytable'
ORDER BY t1.[TABLE_NAME], t1.[TABLE_SCHEMA], t1.[ORDINAL_POSITION]
Johan
Learn to play, play to learn !
Dont drive faster than your guardian angel can fly ...
but keeping both feet on the ground wont get you anywhere :w00t:
- How to post Performance Problems
- How to post data/code to get the best help[/url]
- How to prevent a sore throat after hours of presenting ppt
press F1 for solution, press shift+F1 for urgent solution 😀
Need a bit of Powershell? How about this
Who am I ? Sometimes this is me but most of the time this is me
January 6, 2009 at 1:27 pm
Sorry ALZDBA - I am only on sqlserver2000 !
Liked the bike on yor profile pic !
😎
January 6, 2009 at 1:42 pm
Please post SQL 2000-related questions in the SQL 2000 forums. If you post in the 2005 forums, you're very likely to get 2005-specific solutions.
The Information schema exists in 2000 as well, and looks the same as it does in 2005.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
January 6, 2009 at 1:43 pm
apologies - just noticed it was the 2005 forum
January 6, 2009 at 2:53 pm
Continued here - http://www.sqlservercentral.com/Forums/Topic630987-169-1.aspx
No more replies to this thread please.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply